1、相關插件準備
vue、vue-wait、axios
2、在main.js引入vue-wait
引入步驟如下,具體vue-wait說明請查看 https://github.com/f/vue-wait/tree/master
import VueWait from 'vue-wait'
//Loading集中管理控件
Vue.use(VueWait) // add VueWait as Vue plugin
let wait = new VueWait({ registerComponents: false })
window.$wait = wait
new Vue({
store,
router,
render: h => h(App),
wait:wait
}).$mount('#app');
3、axios請求方法編寫
這裏主要是在config中配置自定義屬性loadingLoader,屬性值隨你定。
export default {
// get
getTestList (params) {
return axios.get('/api/getTestList', {params: params, loadingLoader:'getTestList'})
},
// post
postData(params) {
return axios.post('/api/xxx', params, {loadingLoader: 'postData'})
},
}
4、axios配置攔截器
在進行ajax請求時,獲取配置的config, 根據config中的loadingLoader自動攔截,修改loading狀態。
但是要注意,新版的axios在使用攔截器攔截,無法拿到config中自定義屬性。我們可以使用老版本axios 0.15.3或者自行修改axios源碼。
import axios from 'axios'
function requestInterceptors(config){
/** 如果有loading Loader,開啓wait插件 */
if (config && config.loadingLoader) {
window.$wait.start(config.loadingLoader)
return
}
}
function responseInterceptors(config){
/** 清除該請求的loading載體 */
if (config && config.loadingLoader) {
window.$wait.end(config.loadingLoader)
return
}
}
axios.interceptors.request.use(
config => {
let authorization = localStorage.getItem('authorization')
if (authorization) {
config.headers.authorization = authorization
}
requestInterceptors(config)
return config
},
err => {
responseInterceptors(err.config)
return Promise.reject(err)
}
)
axios.interceptors.response.use(
response => {
responseInterceptors(response.config)
return response
},
error => {
responseInterceptors(error.config)
return Promise.reject('服務器出錯,請重試')
}
)
export default axios
5、組件內使用
<template>
<div>
/**$wait.is()該方法的參數可以是數組,也可以是字符串,取決於
你希望由哪些請求來控制容器的加載狀態,這裏面的參數值是上一步在axios請求中寫的loadingLoder值,
$wait.is('getTestList') 會在axios請求'/api/getTestList'自動變爲true,結束請求時變爲false。
無需我們再手動控制loading狀態 **/
<el-table v-loading="$wait.is('getTestList')">
/**省略中間代碼**/
</el-table>
</div>
</template>
<script>
import api from '@/api'
export default {
name: '測試',
data () {
return {}
},
mounted () {
this.getData()
},
methods: {
getData(){
//調用第4步的api接口獲取數據
api.getTestList({params1:'',params2:''}).then().catch(err=>{
})
}
}
}
</script>
<style scoped>
</style>