[Vuejs]-How to detect click on children vue/nux custom directive

0👍

In the snippet below:

  • if you click on the red, it’s the parent element
  • if you click on the blue-title, it’s the title element
  • if you click on the blue-close, it’s the close element
  • if you click outside the parent element, it’s outside
Vue.directive('DropdownDirective', {
  bind(el, binding) {
    let type = binding.arg;
    const clickFunction = (e) => {
      if (e.target.classList.contains('close')) {
        console.log('close')
      } else if (e.target.classList.contains('title')) {
        console.log('title:', e.target.textContent)
      } else if (e.target === el) {
        console.log('parent')
      } else {
        console.log('outside')
      }
    }
    // adding a general eventListener, so you can check for clicks outside
    window.addEventListener(type, clickFunction);
  }
})

new Vue({
  el: "#app"
})
.dd-item {
  width: 50%;
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-dropdown-directive:click class="dropdown" style="background-color:red;">
    <div class="title dd-item">This is dropdown title</div>
    <div class="close dd-item">Close dropdown</div>
  </div>
</div>

The point is:

  • you have to define the event you want to listen for. In the snippet I defined it as an argument of the directive (:click), and use that argument in the directive binding
  • you have to add the listener to that event (as you would have to with any JS code that should listen to an event)
  • you have to define the callback function of that eventListener

More on Vue directives: https://v2.vuejs.org/v2/guide/custom-directive.html

Leave a comment