vue中axios基本用法

1.首先安装axios:

1):npm install

2):npm install vue-axios --save

3):npm install qs.js --save  //这一步可以先忽略,它的作用是能把json格式的直接转成data所需的格式

2.安装成功后,在main.js页面引用:

import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$axios = axios    //全局注册,使用方法为:this.$axios
Vue.prototype.qs = qs           //全局注册,使用方法为:this.qs

3.最后开始使用请求:

<script>
    export default{
    
    
        data(){
    
    
            return{
    
    
                userId:666,
          token:'',
            }
        },
        created(){
    
    
            this.$axios({
    
    
                method:'post',
                url:'api',
                data:this.qs.stringify({
    
        //这里是发送给后台的数据
                      userId:this.userId,
                      token:this.token,
                })
            }).then((response) =>{
    
              //这里使用了ES6的语法
                console.log(response)       //请求成功返回的数据
            }).catch((error) =>
                console.log(error)       //请求失败返回的数据
            })
        }
    }
</script>

同时发起多个请求function getUserAccount() {

  return axios.get('/user/12345');
}

function getUserPermissions() {
    
    
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    
    
    // Both requests are now complete
  }));

创建一个实例
你可以创建一个拥有通用配置的axios实例

axios.creat([config])
var instance = axios.create({
    
    
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {
    
    'X-Custom-Header': 'foobar'}
});

原文地址
中文讲解:lewis1990@amoy
https://www.cnblogs.com/silent007/p/8603367.html
https://www.cnblogs.com/wang-man/p/9531339.html (移除了拦截器。)

https://www.cnblogs.com/sybboy/p/7249987.html (知识讲解点)

作者:阳光之城alt
链接:https://www.jianshu.com/p/fd7bf46d4412
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/qq_41353397/article/details/113448085