Skip to content

Commit

Permalink
refactor(useOnResize): clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
07akioni committed Dec 19, 2024
1 parent d72ae66 commit 312d133
Showing 1 changed file with 16 additions and 21 deletions.
37 changes: 16 additions & 21 deletions src/_utils/composable/use-resize.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,9 @@
import { onBeforeUnmount, onMounted, type Ref } from 'vue'
import { onBeforeUnmount, onMounted, type Ref, watch } 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,
options?: UseOnResizeOptions
onResize: (() => void) | undefined
): void {
// it needn't be reactive since it's for internal usage
if (onResize) {
Expand All @@ -23,20 +13,25 @@ export function useOnResize(
resizeObserverManager.registerHandler(el, onResize)
}
})

// avoid memory leak
watch(
elRef,
(_, oldEl) => {
if (oldEl) {
resizeObserverManager.unregisterHandler(oldEl)
}
},
{
deep: false
}
)

onBeforeUnmount(() => {
const { value: el } = elRef
if (el) {
resizeObserverManager.unregisterHandler(el)
}
})
if (options?.show && isRef(options.show)) {
onBeforeUpdate(() => {
const { value: el } = elRef
const { value: show } = options.show!
if (!show && el) {
resizeObserverManager.unregisterHandler(el)
}
})
}
}
}

0 comments on commit 312d133

Please sign in to comment.