mirror of
https://gitee.com/vant-contrib/vant.git
synced 2025-04-06 03:57:59 +08:00
feat(@vant/use): watch target change (#9077)
* feat(@vant/use): watch target change * types: TargetRef
This commit is contained in:
parent
0a4fc0507c
commit
f536bd683a
@ -1,4 +1,4 @@
|
||||
import { Ref, unref, onUnmounted, onDeactivated } from 'vue';
|
||||
import { Ref, unref, onUnmounted, onDeactivated, watch } from 'vue';
|
||||
import { onMountedOrActivated } from '../onMountedOrActivated';
|
||||
import { inBrowser } from '../utils';
|
||||
|
||||
@ -18,8 +18,10 @@ if (inBrowser) {
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
type TargetRef = EventTarget | Ref<EventTarget | undefined>;
|
||||
|
||||
export type UseEventListenerOptions = {
|
||||
target?: EventTarget | Ref<EventTarget | undefined>;
|
||||
target?: TargetRef;
|
||||
capture?: boolean;
|
||||
passive?: boolean;
|
||||
};
|
||||
@ -37,7 +39,7 @@ export function useEventListener(
|
||||
|
||||
let attached: boolean;
|
||||
|
||||
const add = () => {
|
||||
const add = (target?: TargetRef) => {
|
||||
const element = unref(target);
|
||||
|
||||
if (element && !attached) {
|
||||
@ -50,7 +52,7 @@ export function useEventListener(
|
||||
}
|
||||
};
|
||||
|
||||
const remove = () => {
|
||||
const remove = (target?: TargetRef) => {
|
||||
const element = unref(target);
|
||||
|
||||
if (element && attached) {
|
||||
@ -59,7 +61,12 @@ export function useEventListener(
|
||||
}
|
||||
};
|
||||
|
||||
onUnmounted(remove);
|
||||
onDeactivated(remove);
|
||||
onMountedOrActivated(add);
|
||||
onUnmounted(() => remove(target));
|
||||
onDeactivated(() => remove(target));
|
||||
onMountedOrActivated(() => add(target));
|
||||
|
||||
watch(target, (val, oldVal) => {
|
||||
remove(oldVal);
|
||||
add(val);
|
||||
});
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user