下面是一個簡易的axios攔截器使用的demo,主要看下代碼注釋,詳細可參考axios官方API
axios
let app = new Vue({
el: "#app",
data() {
return {
isLoading: false, //loading組件
}
},
mounted() {
this.getAxios();
},
methods: {
getAxios() {
let _this = this;
//這是一個axios的請求攔截器,在我們請求之前做一些事情(比如加載loading)
axios.interceptors.request.use(function(config) {
// 顯示loading
_this.isLoading = true;
return config
}, function(error) {
// 請求錯誤時彈框提示,或做些其他事
_this.isLoading = false;
return Promise.reject(error)
})
//這是axios的一個請求
axios.get('https://api.wrdan.com/hitokoto').then((res) => {
_this.isLoading = false; //請求成功隱藏掉loading
console.log(res)
}).catch((err) => {
_this.isLoading = false;
console.log(err)
})
}
},
})
// 剛我們說了請求式攔截器,還有一種回應攔截器
axios.interceptors.response.use( function ( response ) { // 對回應資料做一些事情return response; }, function ( error ) { // 對回應做一些事情錯誤return Promise .reject(error) ; });
//再說一下清除攔截器(先宣告一個我們所需的攔截器,跟上面一樣的,就多了個宣告)
const myInterceptor = axios.interceptors.request.use(函式() {/*...*/});
//然后在不想使用的地方清除
axios.interceptors.request.eject(myInterceptor);
更多使用請詳情查閱 axios 官方api
end~~~
如有錯誤或觀點不一致的請評論留言共同討論,本人前端小白一枚,根據自己實際專案遇到的問題進行總結分享,謝謝大家的閱讀!
文章對您有所幫助請給作者點個贊支持下,謝謝~
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/292070.html
標籤:其他
下一篇:Glide原始碼學習-三大快取
