Vue基于vuex、axios攔截器實現(xiàn)loading效果及axios的安裝配置
準備
- 利用vue-cli腳手架創(chuàng)建項目
- 進入項目安裝vuex、axios(npm install vuex,npm install axios)
axios配置
項目中安裝axios模塊(npm install axios)完成后,進行以下配置:
main.js
//引入axios import Axios from 'axios' //修改原型鏈,全局使用axios,這樣之后可在每個組件的methods中調(diào)用$axios命令完成數(shù)據(jù)請求 Vue.prototype.$axios=Axios
loading組件
我這里就選擇使用iview提供的loading組件,
npm install iview
main.js import iView from 'iview'; import 'iview/dist/styles/iview.css'; Vue.use(iView);
安裝引入后,將loading寫成一個組件loading.vue

Vuex state狀態(tài)設置控制loading的顯隱
store.js(Vuex)
export const store = new Vuex.Store({
state:{
isShow:false
}
})
在state中定義isShow屬性,默認false隱藏
v-if="this.$store.state.isShow"
為loading組件添加v-if綁定state中的isShow
組件使用axios請求數(shù)據(jù)
<button @click="getData">請求數(shù)據(jù)</button>
methods:{
getData(){
this.$axios.get('https://www.apiopen.top/journalismApi')
.then(res=>{
console.log(res)//返回請求的結(jié)果
})
.catch(err=>{
console.log(err)
})
}
}
我這里使用一個按鈕進行觸發(fā)事件,利用get請求網(wǎng)上隨便找的一個api接口,.then中返回請求的整個結(jié)果(不僅僅包括數(shù)據(jù))
Axios攔截器配置
main.js
//定義一個請求攔截器
Axios.interceptors.request.use(function(config){
store.state.isShow=true; //在請求發(fā)出之前進行一些操作
return config
})
//定義一個響應攔截器
Axios.interceptors.response.use(function(config){
store.state.isShow=false;//在這里對返回的數(shù)據(jù)進行處理
return config
})
分別定義一個請求攔截器(請求開始時執(zhí)行某些操作)、響應攔截器(接受到數(shù)據(jù)后執(zhí)行某些操作),之間分別設置攔截時執(zhí)行的操作,改變state內(nèi)isShow的布爾值從而控制loading組件在觸發(fā)請求數(shù)據(jù)開始時顯示loading,返回數(shù)據(jù)時隱藏loading
特別注意:這里有一個語法坑(我可是來來回回踩了不少次)main.js中調(diào)取、操作vuex state中的數(shù)據(jù)不同于組件中的this.$store.state,而是直接store.state 同上面代碼
效果展示


總結(jié)
以上所述是小編給大家介紹的Vue基于vuex、axios攔截器實現(xiàn)loading效果及axios的安裝配置,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
相關文章
關于iview按需引用后使用this.$Modal報錯的解決
這篇文章主要介紹了關于iview按需引用后使用this.$Modal報錯的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

