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 { onMountedOrActivated } from '../onMountedOrActivated';
|
||||||
import { inBrowser } from '../utils';
|
import { inBrowser } from '../utils';
|
||||||
|
|
||||||
@ -18,8 +18,10 @@ if (inBrowser) {
|
|||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type TargetRef = EventTarget | Ref<EventTarget | undefined>;
|
||||||
|
|
||||||
export type UseEventListenerOptions = {
|
export type UseEventListenerOptions = {
|
||||||
target?: EventTarget | Ref<EventTarget | undefined>;
|
target?: TargetRef;
|
||||||
capture?: boolean;
|
capture?: boolean;
|
||||||
passive?: boolean;
|
passive?: boolean;
|
||||||
};
|
};
|
||||||
@ -37,7 +39,7 @@ export function useEventListener(
|
|||||||
|
|
||||||
let attached: boolean;
|
let attached: boolean;
|
||||||
|
|
||||||
const add = () => {
|
const add = (target?: TargetRef) => {
|
||||||
const element = unref(target);
|
const element = unref(target);
|
||||||
|
|
||||||
if (element && !attached) {
|
if (element && !attached) {
|
||||||
@ -50,7 +52,7 @@ export function useEventListener(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const remove = () => {
|
const remove = (target?: TargetRef) => {
|
||||||
const element = unref(target);
|
const element = unref(target);
|
||||||
|
|
||||||
if (element && attached) {
|
if (element && attached) {
|
||||||
@ -59,7 +61,12 @@ export function useEventListener(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
onUnmounted(remove);
|
onUnmounted(() => remove(target));
|
||||||
onDeactivated(remove);
|
onDeactivated(() => remove(target));
|
||||||
onMountedOrActivated(add);
|
onMountedOrActivated(() => add(target));
|
||||||
|
|
||||||
|
watch(target, (val, oldVal) => {
|
||||||
|
remove(oldVal);
|
||||||
|
add(val);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user