在后台系统里,频繁地加载数据是常态,因此在等待后台响应的过程当中,如何统1、最少的代码来处理加载状态,多是咱们每一个FE须要考虑的事情,如今我提供一个我的的解决思路vue
使用 npm install element 后,在 main.js 文件里引入element,能够完整引入 import ElementUI from 'element-ui';
。 也能够按需引入 import { Loading } from 'element-ui';
,引入后Vue.use(Loading);
。ios
Vue.prototype
上有一个全局方法$loading
,调用this.$loading(options)
能够返回Loading
实例。Loading
:使用Loading.servie
(返回一个 Loading
实例)来代替Vue.prototype
的$loading
方法,使用Vue.prototype.$loading = Loading.servic
.由于加载是与后台请求时触发的,因此,先处理请求部分:vuex
vue.prototype
上添加一个新的属性。import * as actions from 'vuexx/actions';
Vue.prototype.$actions = actions;
复制代码
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;
};
复制代码
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 此值进行处理。npm
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官网element-ui
当须要使用 fullLoading 时,在 api 文件里,新增接口,而且配置 options._fullpageLoad = true;
,在须要的地方调用便可,例如:axios
this.$actions.apixxx(
param,
result => {
},
err => {
}
);
复制代码
以为不错的,点个赞哦,欢迎交流~api