Detect click outside element

There is the solution I used, which is based on Linus Borg answer and works fine with vue.js 2.0.

Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.clickOutsideEvent = function (event) {
      // here I check that click was outside the el and his children
      if (!(el == event.target || el.contains(event.target))) {
        // and if it did, call method provided in attribute value
        vnode.context[binding.expression](event);
      }
    };
    document.body.addEventListener('click', el.clickOutsideEvent)
  },
  unbind: function (el) {
    document.body.removeEventListener('click', el.clickOutsideEvent)
  },
});

You bind to it using v-click-outside:

<div v-click-outside="doStuff">

Here’s a small demo

You can find some more info about custom directives and what el, binding, vnode means in https://vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments

Leave a Comment