Basic usage of axios in vue

1. First install axios:

1):npm install

2):npm install vue-axios --save

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

2. After the installation is successful, quote on the main.js page:

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

3. Finally, start to use the request:

<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>

Initiate multiple requests at the same time 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
  }));

Create an instance
You can create an axios instance with a common configuration

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

Original address
Chinese explanation: lewis1990@amoy
https://www.cnblogs.com/silent007/p/8603367.html
https://www.cnblogs.com/wang-man/p/9531339.html (Blocker removed .)

https://www.cnblogs.com/sybboy/p/7249987.html (knowledge explanation point)

Author: City of Sunshine alt
link: https: //www.jianshu.com/p/fd7bf46d4412
Source: Jane books
are copyrighted by the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_41353397/article/details/113448085