Posts Learn Components Snippets Categories Tags About
/

How to Define Vue Js Click Away Directive

Learn how to define Vue Js click away directive to trigger a function when the user clicks outside of the bound element

Created on Sep 11, 2021

8 views

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>

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for How to Define Vue Js Click Away Directive

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More