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