怎么用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.js插图片

vue-material是什么?

vue脚手架搭建流程

.js文件中怎么引用vue

vue基于iview table展示图片实现点击放大功能

如何解决vue $index报错问题

vue项目通过import引入外部css报错怎么办

了解一下vue中的插槽

vue中递归组件的实现方法介绍(附实例:三级菜单)

angular脏值检测与vue数据劫持的区别是什么

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




打赏

取消

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

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

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

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

评论

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