美文网首页
vue使用axios

vue使用axios

作者: 紫气楠楠 | 来源:发表于2019-12-03 12:27 被阅读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是上面请求返回的数据
})
```

相关文章

网友评论

      本文标题:vue使用axios

      本文链接:https://www.haomeiwen.com/subject/grtwmctx.html