[Vuejs]-Vue directive not triggering method

0👍

Credits to Linus Borg who answered my question for me on the forum. Was just understanding the purpose of events incorrectly.

Events are usually used to communicate from a child component to a parent component, so triggering an event ‘close’ in a componet will not run a method of that name in that component.

If you want that, you have to actually register a listener to that event:

created () {
  this.$on('close', this.close /*the name of the method to call */)
}

However, this isn’t really necessary in your case. you are already passing the close method to the directive, so you can run it directly:

Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {

    document.addEventListener(clickHandler, (event) => {
      const clickedInsideDropdown = el.contains(event.target);

      if (!clickedInsideDropdown && el.classList.contains(openClass)) {
        binding.value()

        // alternartively, you could also call the method directly on the instance, no need for an event: 
        vnode.context.[expression]()
        // but that wouldn't really be elegant, agreed?
      }
    });
  }
});
👤Austin

Leave a comment