1.首先安裝axios:
1):npm install
2):npm install vue-axios --save
3):npm install qs.js --save //這一步可以先忽略隘膘,它的作用是能把json格式的直接轉(zhuǎn)成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({ //這里是發(fā)送給后臺的數(shù)據(jù)
userId:this.userId,
token:this.token,
})
}).then((response) =>{ //這里使用了ES6的語法
console.log(response) //請求成功返回的數(shù)據(jù)
}).catch((error) =>
console.log(error) //請求失敗返回的數(shù)據(jù)
})
}
}
</script>
同時發(fā)起多個請求
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
}));
創(chuàng)建一個實例
你可以創(chuàng)建一個擁有通用配置的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 (移除了攔截器。)