How to detect click outside element with Vue.js?

Sometimes, we want to detect click outside element with Vue.js.

In this article, we’ll look at how to detect click outside element with Vue.js.

How to detect click outside element with Vue.js?

To detect click outside element with Vue.js, we can add a directive to detect the clicks.

For instance, we write

Vue.directive("click-outside", {
  bind(el, binding, vnode) {
    el.clickOutsideEvent = (event) => {
      if (!(el == event.target || el.contains(event.target))) {
        vnode.context[binding.expression](event);
      }
    };
    document.body.addEventListener("click", el.clickOutsideEvent);
  },
  unbind(el) {
    document.body.removeEventListener("click", el.clickOutsideEvent);
  },
});

to call Vue.directive to create the click-outside directive.

In the bind method, we check if the click is outside an element with !(el == event.target || el.contains(event.target)).

And if it’s outside, we call the event handler we set as the value of the directive with vnode.context[binding.expression](event).

We listen for clicks by calling document.body.addEventListener with 'click'.

And we unbind the event listener with document.body.removeEventListener.

Conclusion

To detect click outside element with Vue.js, we can add a directive to detect the clicks.