41 lines
1.2 KiB
JavaScript
41 lines
1.2 KiB
JavaScript
import Vue from 'vue';
|
||
|
||
/**
|
||
* 自动恢复加载状态的指令
|
||
* 用法: v-loading-recovery="{ loading: 'loadingProp', recovery: ['method1', 'method2'] }"
|
||
*/
|
||
export const loadingRecoveryDirective = {
|
||
// 当绑定元素插入到 DOM 中时
|
||
inserted(el, binding, vnode) {
|
||
const component = vnode.context;
|
||
const { loading, recovery } = binding.value || {};
|
||
|
||
if (!loading || !recovery || !Array.isArray(recovery)) return;
|
||
|
||
// 为组件添加加载状态恢复的逻辑
|
||
const handleNetworkRecovery = () => {
|
||
// 当网络恢复时,自动设置loading为false
|
||
if (component[loading]) {
|
||
component[loading] = false;
|
||
}
|
||
};
|
||
|
||
// 保存到元素上,以便后续清理
|
||
el._loadingRecovery = handleNetworkRecovery;
|
||
window.addEventListener('network-retry-complete', handleNetworkRecovery);
|
||
|
||
console.log(`[LoadingRecovery] 添加加载状态恢复: ${loading}`);
|
||
},
|
||
|
||
// 当指令与元素解绑时
|
||
unbind(el) {
|
||
// 清理事件监听
|
||
if (el._loadingRecovery) {
|
||
window.removeEventListener('network-retry-complete', el._loadingRecovery);
|
||
delete el._loadingRecovery;
|
||
}
|
||
}
|
||
};
|
||
|
||
// 注册全局指令
|
||
Vue.directive('loading-recovery', loadingRecoveryDirective); |