Skip to content

Commit

Permalink
fix(cascader): fix memory leak caused by event listener (#6313)
Browse files Browse the repository at this point in the history
Co-authored-by: 07akioni <[email protected]>
  • Loading branch information
Zheng-Changfu and 07akioni authored Dec 19, 2024
1 parent 41db9e6 commit d72ae66
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
21 changes: 20 additions & 1 deletion src/_utils/composable/use-resize.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import { onBeforeUnmount, onMounted, type Ref } from 'vue'
import { resizeObserverManager } from 'vueuc'

interface UseOnResizeOptions {
/**
* In some cases
* if a reactive variable is used in the render function to control whether or not the dom is rendered,
* the event cannot be cleared in onBeforeUnmount because the dom no longer exists,
* but the event contains a reference to the dom, resulting in a memory leak
*/
show?: Ref<boolean>
}
export function useOnResize(
elRef: Ref<HTMLElement | null>,
onResize: (() => void) | undefined
onResize: (() => void) | undefined,
options?: UseOnResizeOptions
): void {
// it needn't be reactive since it's for internal usage
if (onResize) {
Expand All @@ -19,5 +29,14 @@ export function useOnResize(
resizeObserverManager.unregisterHandler(el)
}
})
if (options?.show && isRef(options.show)) {

Check failure on line 32 in src/_utils/composable/use-resize.ts

View workflow job for this annotation

GitHub Actions / lint (18)

Cannot find name 'isRef'.

Check failure on line 32 in src/_utils/composable/use-resize.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Cannot find name 'isRef'.
onBeforeUpdate(() => {

Check failure on line 33 in src/_utils/composable/use-resize.ts

View workflow job for this annotation

GitHub Actions / lint (18)

Cannot find name 'onBeforeUpdate'.

Check failure on line 33 in src/_utils/composable/use-resize.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Cannot find name 'onBeforeUpdate'.
const { value: el } = elRef
const { value: show } = options.show!
if (!show && el) {
resizeObserverManager.unregisterHandler(el)
}
})
}
}
}
3 changes: 2 additions & 1 deletion src/cascader/src/CascaderMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
inject,
type PropType,
ref,
toRef,
Transition,
withDirectives
} from 'vue'
Expand Down Expand Up @@ -74,7 +75,7 @@ export default defineComponent({
function handleResize(): void {
syncCascaderMenuPosition()
}
useOnResize(selfElRef, handleResize)
useOnResize(selfElRef, handleResize, { show: toRef(props, 'show') })
function showErrorMessage(label: string): void {
const {
value: { loadingRequiredMessage }
Expand Down

0 comments on commit d72ae66

Please sign in to comment.