vue.js请求数据(axios)

本文介绍了如何使用npm安装Axios,并将其注册到Vue中以便全局调用。演示了GET和POST请求的具体实现方法,同时提供了并发执行多个请求的示例。

使用npm安装axios

npm install axios --save

在main.js中引入axios

import axios from "axios";

注册axios到vue,注册axios到vue不能使用use方法(Vue.use(axios))

Vue.prototype.$http = axios;//$http为自定义的,Vue.prototype 为注册全局方法 其他任何组件都可以使用

之后就可以到页面使用

执行GET请求

<script type="text/ecmascript-6">
  export default {
    methods: function () {
      this.$http.get('/user', {"id": 123})
    .then(res => { console.log(res.data); })
    .catch(err => {
     console.log(err.msg)
    }) } };
</script>

 

执行POST请求

<script type="text/ecmascript-6">
  export default {
    methods: function () {
      this.$http.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
   .then(
res => { console.log(res.data); })
   .
catch(err => { console.log(err.msg); }) } }; </script>

一次并发多个请求

function getUserAccount(){
  return axios.get('/user');
}
function getUserPermissions(){
  return axios.get('/user/permissions');
}
axios.all([getUserAccount(),getUserPermissions()])
  .then(axios.spread(function(acct,perms){
    //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果
}))

 

转载于:https://www.cnblogs.com/YAN-HUA/p/9143993.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值