Click away directive



const showMenu = ref(false)

app.directive('click-away', {
    created: (el, binding) => {
      el.clickListener = (e) => {
        // e.preventDefault()
        if (!el.contains(e.target)) {
          binding.value()
        }
      }
      document.addEventListener('click', el.clickListener)
    },
    beforeUnmount: (el, /*binding*/) => {
      document.removeEventListener('click', el.clickListener)
    },
  })


Usage


<div v-click-away="() => showMenu = false" @click.stop="showMenu = true">
Menu Here
</div>


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *