mirror of
https://gitee.com/vant-contrib/vant.git
synced 2025-04-06 03:57:59 +08:00
feat: useHandler add ref param
This commit is contained in:
parent
0d5b53d2a5
commit
b6549ed721
@ -1,28 +1,44 @@
|
|||||||
import { on, off } from '../utils';
|
import { on, off } from '../utils/dom/event';
|
||||||
import { onMounted, onActivated, onUnmounted, onDeactivated } from 'vue';
|
import {
|
||||||
|
Ref,
|
||||||
|
watch,
|
||||||
|
onMounted,
|
||||||
|
onActivated,
|
||||||
|
onUnmounted,
|
||||||
|
onDeactivated
|
||||||
|
} from 'vue';
|
||||||
|
|
||||||
export function useHandler(
|
export function useHandler(
|
||||||
target: HTMLElement | Document | Window,
|
target: HTMLElement | Document | Window,
|
||||||
event: string,
|
event: string,
|
||||||
handler: any,
|
handler: any,
|
||||||
passive = false
|
passive = false,
|
||||||
|
ref?: Ref<boolean>
|
||||||
) {
|
) {
|
||||||
let added: boolean;
|
let binded: boolean;
|
||||||
|
|
||||||
function add() {
|
function add() {
|
||||||
if (!added) {
|
if (binded || (ref && !ref.value)) {
|
||||||
on(target, event, handler, passive);
|
return;
|
||||||
added = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
on(target, event, handler, passive);
|
||||||
|
binded = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function remove() {
|
function remove() {
|
||||||
if (added) {
|
if (binded) {
|
||||||
off(target, event, handler);
|
off(target, event, handler);
|
||||||
added = false;
|
binded = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (ref) {
|
||||||
|
watch(() => {
|
||||||
|
ref.value ? add() : remove();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(add);
|
onMounted(add);
|
||||||
onActivated(add);
|
onActivated(add);
|
||||||
onUnmounted(remove);
|
onUnmounted(remove);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user