Sometimes, we want to handle click and dblclick events on same element with Vue.js.
In this article, we’ll look at how to handle click and dblclick events on same element with Vue.js.
How to handle click and dblclick events on same element with Vue.js?
To handle click and dblclick events on same element with Vue.js, we just use the click handler and watch for a second in there.
For instance, we write
<template>
<ul class="data_row" v-for="(row, index) in gridData" @click="oneClick">
...
</ul>
</template>
<script>
//...
export default {
//...
methods: {
oneClick(event) {
this.clicks++;
if (this.clicks === 1) {
this.timer = setTimeout(() => {
this.result.push(event.type);
this.clicks = 0;
}, this.delay);
} else {
clearTimeout(this.timer);
this.result.push("dblclick");
this.clicks = 0;
}
},
},
//...
};
</script>
to watch for clicks with the oneClick
method.
In it, we track the number of clicks with the this.clicks
reactive property.
If we detected one click by checking that this.clicks === 1
, then we call setTimeout
to start a timer to push the event.type
in this.delay
milliseconds and reset this.clicks
to 0.
Otherwise, we call clearTimeout
to clwar the timer and push
'dblclick'
since there’re 2 clicks done in a short amount of time.
And then we reset this.clicks
to 0.
Conclusion
To handle click and dblclick events on same element with Vue.js, we just use the click handler and watch for a second in there.