怎么用vue.js做异步请求


本文摘自PHP中文网,作者藏色散人,侵删。

用vue.js做异步请求的方法:首先在项目中安装axiox;然后在main.js中引入axiox,以供全局使用;接着进行axios get请求;最后实现axios post请求即可。

本教程操作环境:windows7系统、vue2.0版本、thinkpad t480电脑。

推荐:《vue教程》

用vue.js做异步请求

一、axios实现异步请求

1.项目中安装axiox

1

npm install --save axios

2.在main.js中引入以供全局使用

1

2

3

4

5

import axios from 'axios'

//可以给axios的ajax请求设置统一的主机和端口号

axios.defaults.baseURL = "http://157.122.54.189:8080/";

//将axios这个对象添加到Vue的原型对象中,在使用的时候就只需要使用this.对象名就可以了

Vue.prototype.$http = axios

3.axios之get请求

vue前端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<template>

 <div>

 </div>

</template>

<script>

export default {

  methods:{

   getData(){

   //axios-get请求

   this.$http.get('/getData1')

         .then(r => console.log(r))//接口调用成功返回的数据

         .catch(err => console.log(err)),//接口调用失败返回的数据

    }

  }

  mounted(){//模板或el对应的html渲染完成后再调用里面的方法

 this.getData()

  }

}

</script>

<style scoped>

</style>

node后端:

server.get('/getData1',function(req,res){

  res.send({

    'msg':'aaa'

  })

})

请求结果:

7bf16a8adc3c4428e1b8c0684c38f69.png

4.axios之post请求

Vue前端:

阅读剩余部分

相关阅读 >>

浅析vue创建组件的几种方式

vue bootstrap区别

使用vue脚手架怎么搭建项目

vue组件中如何引入css文件

vue路由守卫有哪三种类型

如何解决vue中layui报错问题

vue-loader是什么?

bootstrap和vue的区别

vue实现户籍管理系统的实例解析

vuex中mutations怎么理解?怎么用?

更多相关阅读请进入《vue》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...