这套代码是基础vue中自定义指令directive编写的
功能:如果在一个位置长按两秒(不动)则进入自定义指令回调方法,如果在一个位置长按然后带有拖动(滚动行为)则不进入自定义指令回调方法
场景:相册的长按进入编辑功能
创建:src/plugins/longclick.js
let timerId = null;
let isMoving = false;
const onTouchStart = (el, binding) => {
const { value } = binding;
// 开始计时
timerId = setTimeout(() => {
if (!isMoving && typeof value === "function") {
value();
}
}, 800);
};
const onTouchMove = () => {
isMoving = true;
clearTimeout(timerId);
};
const onTouchEnd = () => {
clearTimeout(timerId);
isMoving = false;
};
const longclick = {
mounted(el, binding) {
el.addEventListener("touchstart", () => {
onTouchStart(el, binding);
});
el.addEventListener("touchmove", onTouchMove);
el.addEventListener("touchend", onTouchEnd);
},
unmounted(el) {
el.removeEventListener("touchstart", () => onTouchStart(el, binding));
el.removeEventListener("touchmove", onTouchMove);
el.removeEventListener("touchend", onTouchEnd);
},
};
export default longclick;
main.js导入
注意点:使用时候一定加上:v-自定义指令名称
import { createApp } from "vue";
import App from "./App.vue";
import longclick from "@/plugins/longclick"; //导入自定义指令方法
const app = createApp(App);
app.directive("longclick", longclick); //挂载全局
app.mount("#app");
组件使用
<template>
<div class="main">
<div v-for="item in 1000">
<img src="您的图片地址" class="img" v-longclick="handle"></img>
</div>
</div>
</template>
<script setup>
const handle = ()=>{
console.log("进入了编辑状态")
}
</script>
<style>
.main{
width:100%;
height:500px;
overflow:auto; //一定要设置auto才有滚动条
}
.img{
display:block;
width:100%;
height:100px; //内容高度比父盒子搞,出现滚动条
}
</style>