feat(@vant/use): watch target change (#9077)

* feat(@vant/use): watch target change

* types: TargetRef
This commit is contained in:
neverland 2021-07-21 16:11:12 +08:00 committed by GitHub
parent 0a4fc0507c
commit f536bd683a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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);
});
}