1:创建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>
2:在APP.vue中引入组件
<template>
<div>
<Mloading/>
</div>
</template>
<script>
import Mloading from "components/loading/loading"
export default {
components: {
Mloading
}
};
</script>
<style lang='stylus' scoped>
</style>
3:在vuex中state.js中定义 isShowLoading=false
4:在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)
})
}
奘倥城
发布了8 篇原创文章 · 获赞 0 · 访问量 124
私信
关注