How can I capture click event on custom directive on Vue.js?

Vlad picture Vlad · Jan 28, 2018 · Viewed 9.2k times · Source

I am trying to learn Vue.js and came to an practice example where I need to implement a custom directive whice works lice 'v-on'. This means that i need to capture the click event on my custom directive and call a method.

The template i was thinking of.

<template>
    <h1 v-my-on:click="alertMe">Click</h1>
</template>

The problem is i don't know how to capture the click event in the custom directive. Excuse the clumsy code below.

<script>
    export default {
        methods: {
            alertMe() {
                alert('The Alert!');
            }
        },
        directives: {
            'my-on': {
                bind(el, binding, vnode) {
                    console.log('bind');

                    el.addEventListener('click',()=>{
                        console.log('bind');
                        vnode.context.$emit('click');
                    });
                },

            }
        }
    }
</script>

Can anyone help me understand how this works? I didn't manage to find any example of something similar.

Answer

Vlad picture Vlad · Jan 28, 2018

After some more searching i came to this solution:


<template>
  <h1 v-my-on:click="alertMe">Click me!</h1>
</template>

<script>

  export default {

    methods: {

      alertMe() {

        alert('The Alert!');

      }

    },

    directives: {

      'my-on': {

        // Add Event Listener on mounted.
        bind(el, binding) {
          el.addEventListener(binding.arg, binding.value);
        },

        // Remove Event Listener on destroy.
        unbind(el, binding) {
          el.removeEventListener(binding.arg, binding.value);
        }

      }

    }

  }
</script>