Handle single and double clicks on the same element in Vue.js

I was looking for a way to handle single click and double click events on the same element in Vue.js. While it looked like 'v-on:dblclick' is going to cover this requirement nicely I soon discovered it’s not ideal. While double clicking 'click' event fires too (as soon as the first click is registered), which makes it hard to handle both types of events separately from each other.

In the end I came up with a component, which relies on the 'click' event to handle both single and double clicks.

<script>
export default {
  render (createElement) {
    return createElement(this.tag, {
      on: {
        click: this.handleClick
      }
    }, this.$slots.default)
  },
  data () {
    return {
      clickCount: 0,
      clickTimer: null
    };
  },
  props: {
    tag: {
      type: String,
      default: 'a'
    },
    delay: {
      type: Number,
      default: 250
    }
  },
  methods: {
    handleClick (e) {
      e.preventDefault()

      this.clickCount++

      if (this.clickCount === 1) {
        this.clickTimer = setTimeout(() => {
          this.clickCount = 0;
          this.$emit('single-click')
        }, this.delay)
      } else if (this.clickCount === 2) {
        clearTimeout(this.clickTimer)
        this.clickCount = 0
        this.$emit('double-click')
      }
    }
  }
};
</script>

The component emits 'single-click' and 'double-click' events:

<double-click @single-click="doThis" @double-click="doThat">
  your content goes here
</double-click>
Did you like this post?
Previous post

I'm interested in functional programming lately and was happy to discover that modifying array keys in PHP can be done avoiding any kind of loops. 😃