For example, the requirement is to add a stand-alone event to a dom or a button, but also to add a double-click event. If it is not processed, when the button is double-clicked, it will execute two stand-alone events and a double-click event;
For example:
<template>
<div >
<button @click="clickHandler" @dblclick="dblclickHandler">注册</button>
</div>
</template>
<script>
export default {
data() {
return {
}
},
created() {
},
mounted() {
},
methods: {
clickHandler() {
console.log('单机事件')
},
dblclickHandler() {
console.log('双击事件')
}
}
}
</script>
If you double-click the button, the console will output:
Solution:
Use a timer to simulate a double-click event at an approximate time
<template>
<div >
<button @click="clickHandler" @dblclick="dblclickHandler">注册</button>
</div>
</template>
<script>
export default {
data() {
return {
timer: null, //添加一个计时器
}
},
created() {
},
mounted() {
},
methods: {
clickHandler() {
clearTimeout(timer); //清除未执行的定时器
timer = setTimeout(function () {
console.log('单机事件')
}, 400);
},
dblclickHandler() {
clearTimeout(timer); //清除未执行的定时器
console.log('双击事件')
}
}
}
</script>
How to write vue3:
let timer = null;
//单击事件
const click=()=>{
clearTimeout(timer); //清除未执行的定时器
timer = setTimeout(function () {
console.log('单击事件'); //单击要执行的事件处理
}, 400);
}
//双击事件
const doubleClick=()=>{
clearTimeout(timer); //清除未执行的定时器
console.log('双击事件'); //双击要执行的事件处理
}