Home / Snippets / How to Define Vue Js Click Away Directive
How to Define Vue Js Click Away Directive cover

How to Define Vue Js Click Away Directive

118

2 years ago

0 comments

To define a directive that triggers a function when the user clicks outside of the bound element in Vue Js, you can write it like below. Having this directive is very powerful when creating a model/popper component that has a clickable backdrop to close/hide the particular component.
<template>
  <div v-clickaway="clickOutside">Hide me</div>
</template>

<script>
Vue.directive('clickaway', {
  bind (el, { value }) {
    if (typeof value !== 'function') {
      console.warn(`Expect a function, got ${value}`);

      return;
    }

    document.addEventListener('click', e => el.contains(e.target) || value());
  }
});

export default {
  methods: {
    clickOutside () {
      // your logic here
    }
  }
}
</script>
notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this