Skip to content

Commit

Permalink
fix(Loading): 处理v-loading指令和useLoading的内存泄露
Browse files Browse the repository at this point in the history
  • Loading branch information
wjc112233 committed May 21, 2024
1 parent 144cdd4 commit b2b19b6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
11 changes: 9 additions & 2 deletions src/components/Loading/src/createLoading.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ export function createLoading(props?: Partial<LoadingProps>, target?: HTMLElemen

vm = createVNode(LoadingWrap);

let container: Nullable<HTMLElement> = null;
if (wait) {
// TODO fix https://github.com/anncwb/vue-vben-admin/issues/438
setTimeout(() => {
render(vm, document.createElement('div'));
container && render(vm, (container = document.createElement('div')));
}, 0);
} else {
render(vm, document.createElement('div'));
render(vm, (container = document.createElement('div')));
}

function close() {
Expand All @@ -41,13 +42,19 @@ export function createLoading(props?: Partial<LoadingProps>, target?: HTMLElemen
target.appendChild(vm.el as HTMLElement);
}

function destory() {
container && render(null, container);
container = vm = null;
}

if (target) {
open(target);
}
return {
vm,
close,
open,
destory,
setTip: (tip: string) => {
data.tip = tip;
},
Expand Down
7 changes: 6 additions & 1 deletion src/components/Loading/src/useLoading.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { unref } from 'vue';
import type { Ref } from 'vue';
import { tryOnUnmounted } from '@vueuse/core';
import { createLoading } from './createLoading';
import type { LoadingProps } from './typing';
import type { Ref } from 'vue';

export interface UseLoadingOptions {
target?: any;
Expand Down Expand Up @@ -45,5 +46,9 @@ export function useLoading(
instance.setTip(tip);
};

tryOnUnmounted(() => {
instance.destory();
});

return [open, close, setTip];
}
2 changes: 1 addition & 1 deletion src/directives/loading.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const loadingDirective: Directive = {
}
},
unmounted(el) {
el?.instance?.close();
el?.instance?.destory();
},
};

Expand Down

0 comments on commit b2b19b6

Please sign in to comment.