test在后台系统里,频繁地加载数据是常态,所以在等待后台响应的过程中,如何统一、最少的代码来处理加载状态,可能是我们每个FE需要考虑的事情,现在我提供一个个人的解决思路
全局引入
使用 npm install element 后,在 main.js 文件里引入element,可以完整引入 import ElementUI from 'element-ui';。 也可以按需引入 import { Loading } from 'element-ui';,引入后Vue.use(Loading);。
全局配置
- 完整引入:
Vue.prototype上有一个全局方法$loading,调用this.$loading(options)可以返回Loading实例。 - 局部引入
Loading:使用Loading.servie(返回一个Loading实例)来代替Vue.prototype的$loading方法,使用Vue.prototype.$loading = Loading.servic.
与vuex结合
因为加载是与后台请求时触发的,所以,先处理请求部分:
- 将所有的 api 放在一个 js 文件里,在 main.js 中全局引入此 js 文件,再在
vue.prototype上添加一个新的属性。
import * as actions from 'vuexx/actions';
Vue.prototype.$actions = actions;
- 在 api 文件内,将每个 axios 请求抽离出公共的处理部分,并且和vuex结合。
import axios from 'axios';
import VueStore from 'vuexx/vue_store';
import {Message} from 'element-ui';
export const apiGlobalGetResource = (param, callback, fallback) => {
let options = {method: 'post', data: param, url: 'common/resource_all'};
// _fullpageLoad用来控制是否loading
options._fullpageLoad = true;
return request(options, callback, fallback);
};
const request = (param, callback, fallback) => {
if (param._fullpageLoad) {
//这里和 vuex 结合
VueStore.commit('setFullpageLoad', true);
}
axios(param)
.then(response => {
let result = response.data;
if (result.code === 200) {
callback(result.data);
} else {
console.log('reject == ', result);
let msg =
result.msg || (result.meta && result.meta.error_message);
if (fallback) {
fallback(msg);
} else if (msg) {
Message.error(msg);
}
}
if (param._fullpageLoad) {
VueStore.commit('setFullpageLoad', false);
}
})
.catch(error => {
let result = error.response || {};
if (
result.status === 502 ||
result.status === 504 ||
error.code === 'ECONNABORTED'
) {
window.setTimeout(() => {
Message.error({
message: '请求超时,请稍后重试',
duration: 0,
showClose: true
});
}, 100);
} else {
console.log('error == ', error);
fallback && fallback(error);
}
if (param._fullpageLoad) {
VueStore.commit('setFullpageLoad', false);
}
});
return source;
};
- 在 vuex 里面,处理
setFullpageLoad即可
const vuStore = new Vuex.Store({
state: {
fullLoading: false
},
mutations: {
setFullpageLoad: function(state, status) {
state.fullLoading = status;
}
}
});
export default vuStore;
实例化
现在我们就可以在一个 vue 文件里注册使用 loading 功能,为了后期最简单地增加 loading 状态,在app.vue里先用计算属性,得到 fullLoading 的值,再 watch 此值进行处理。
computed: {
...mapState({
fullLoading: state => state.fullLoading
})
},
fullLoading: function(newValue) {
if (newValue === true) {
this.loader = this.$loading({
// Loading 需要覆盖的 DOM 节点
target: document.querySelector('.container')
});
} else {
this.loader.close();
}
}
还有别的属性可以配置,更多可查看 Element ui官网
维护
当需要使用 fullLoading 时,在 api 文件里,新增接口,并且配置 options._fullpageLoad = true;,在需要的地方调用即可,例如:
this.$actions.apixxx(
param,
result => {
},
err => {
}
);
觉得不错的,点个赞哦,欢迎交流~