vue使用axios

2019-12-03  本文已影响0人  紫气楠楠

下载

npm install axios --save-dev

引用

import axios from 'axios'

将axios绑定给vue成为一个属性,这样可以在任意组件中使用

//设置axios请求的默认host
//axios.defaults.baseURL = 'https://wechat.kayunzh.com'

//将axios注入到vue原型上
Vue.prototype.$http = axios

使用

get方式
```
this.$http({
    method:'get',
    url:'https://wechat.kayunzh.com/gongzhonghao/Jssdk',
    params:{
        // 代码需要上传服务器,否则返回为0
        url:location.href.split('#')[0],
    }
}).then(res=>{
    this.init(res.data.data)
})
```
post方式
```
this.$http({
    method:'post',
    url:'https://ssl2.xupengfei.net/wx/web_page/getUserInfoByCode',
    data:{
        code:geturlcode
    }
    }).then(res=>{
    if(res.data.code==0){
        this.$store.commit('hasopenId',res.data.data)
    }
    })
```

axios 是基于promise的http库,支持promise API,比如常用的异步回调问题

```
this.$http({
    method:'get',
    url:'https://wechat.kayunzh.com/gongzhonghao/Jssdk',
    params:{
        // 代码需要上传服务器,否则返回为0
        url:location.href.split('#')[0],
    }
}).then(res=>{
    this.init(res.data.data)
    //请求成功后发送下一个请求
    return this.$http({
        //发送请求
    })
}).then(res=>{
    //res是上面请求返回的数据
})
```
上一篇 下一篇

猜你喜欢

热点阅读