- 建立loading.vue
<template>
<div class="loading" v-show="isShowLoading">
<img src="../../common/image/loading.gif" alt="">
<!-- <p class="desc">{{title}}</p> -->
</div>
</template>
<script>
import {mapState} from "vuex";
export default {
props:{
title:{
type:String,
default:'正在載入...'
}
},
computed:{
...mapState(["isShowLoading"])
}
}
</script>
<style scoped lang="stylus">
.loading
width 100%
text-align center
position fixed
left 50%
top 50%
transform translate(-50%)
img
width 200px
height 120px
.desc
line-height 20px
font-size $font-size-small
color $color-text-1
</style>
複製代碼
- 在App.vue在引入組件;
<template>
<div>
<Mloading/>
</div>
</template>
<script>
import Mloading from "components/loading/loading"
export default {
components: {
Mloading
}
};
</script>
<style lang='stylus' scoped>
</style>
複製代碼
- 在vuex中state.js中定義 isShowLoading=false
- 在ajax.js 決定顯示或者隱藏
import axios from 'axios'
import qs from 'qs';
import store from "../store/"
// axios.defaults.baseURL = '/api';
// 是否添加請求頭 // 全局請求頭添加
// axios.defaults.headers.common['Authorization'] = '1234';
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const loadingQueue = {}; //loadingd隊列
// 請求發送前數據攔截攔截器 => 全局請求攔截
axios.interceptors.request.use(function(config) {
/* TODOS使用store進行loading添加 */
config.data = qs.stringify(config.data)
// console.log('loading開始');
if (Object.keys(loadingQueue).length == 0) {
store.state.isShowLoading = true //改變爲true
}
loadingQueue[config.url] = true
return config;
}, function(error) {
return Promise.reject(error);
})
// 請求成功數據攔截器 => 全局請求攔截
axios.interceptors.response.use(function(response) {
/* TODOS 使用store進行loading方法解除 */
// console.log('loading結束');
delete loadingQueue[response.config.url]; //刪除路徑
if (Object.keys(loadingQueue).length == 0) {
store.state.isShowLoading = false //改變爲false
}
return response.data;
}, function(error) {
return Promise.reject(error);
})
export default function({ params = null, url = '', type = 'get' }) {
let data = (type == 'get' || type == 'delete') ? { params } : params;
return new Promise((resolve, reject) => {
axios[type](url, data).then(resolve).catch(reject)
})
}
複製代碼