VUE3 添加长按手势
最近在最海报分享,需要用到长按保存本地
首先移动端并没有直接长按事件,所以我们需要自己模拟一个长按事件。直接上代码
import { App, DirectiveBinding, VNode } from "vue";export default {install: (app: App) => {app.directive("longPress", {mounted(el: any,binding: DirectiveBinding<any>,vnode: VNode<any, any, { [key: string]: any }>,prevVNode: null) {console.log(binding);if (typeof binding.value !== "function") {console.log(`[longpress:] provided expression '${binding.value}' is not afunction, but has to be `);} else {let timer: ReturnType<typeof setTimeout> | null = null;const start = (e: MouseEvent | ToggleEvent) => {if ((<MouseEvent>e).button !== 0 && e.type === "click") {return;}if (timer == null) {timer = setTimeout(() => {handler();}, 500);}};const cancel = () => {if (timer !== null) {clearTimeout(timer);timer = null;}};const handler = () => {binding.value();};// 添加事件监听器el.addEventListener("mousedown", start);el.addEventListener("touchstart", start);// 取消计时器el.addEventListener("click", cancel);el.addEventListener("mouseout", cancel);el.addEventListener("touchend", cancel);el.addEventListener("touchcancel", cancel);}},unmounted(el: any,binding: DirectiveBinding<any>,vnode: VNode<any, any, { [key: string]: any }>,prevVNode: null) {// 添加事件监听器el.removeEventListener("mousedown");el.removeEventListener("touchstart");// 取消计时器el.removeEventListener("click");el.removeEventListener("mouseout");el.removeEventListener("touchend");el.removeEventListener("touchcancel");},});},
};
在 main.ts 文件添加引用
import longPress from "./utils/long-press/index";
createApp(App).use(longPress).mount("#app");
实际使用
// 长按手势 长按 0.5 秒触发<div v-longPress="longPress">长按手势</div>function longPress() {console.log("长按手势触发")}