JSFiddle - React, Tailwind, and code Playground

by lid0

HTML

<script src="https://vuejs.org/js/vue.min.js"></script>
vue 2 - modal capture click outside directive
<div id="vue" style="display:block;width:600px;height:300px;border:4px solid blue">
  <button v-on:click="shown=!shown">
    show
  </button>
  <div class="modal" v-if="shown" style="display:block;width:300px;border:1px solid red;padding:10px" v-click-outside="message">{{message}}</div>

</div>

CSS

body {

  border: 6px solid orange;
  padding: 10px;
}

.modal {
  color: darkgreen;
  width: 300px;
  height: 50px;
  border-radius: 15px;
  background: #fff;
  position: absolute;
  margin-left: auto;
  margin-right: auto;
  left: 160px;
  top:150px;
  -moz-box-shadow: 3px 16px 190px #000;
  -webkit-box-shadow: 3px 16px 190px #000;
  box-shadow: 3px 16px 190px #000;


}

JavaScript

Vue.directive("click-outside", {
  bind(el, binding, vnode) {

    const vm = vnode.context;
    vm.message = binding.value
    const callback = binding.value;
    el.clickOutsideEvent = function(event) {
      console.log(event)
      if (!(el == event.target || el.contains(event.target))) {
        //detect click outside the component
        vm.hide()
      }
    };
    // set capture to true, on add and remove
    document.body.addEventListener("click", el.clickOutsideEvent, true);

  },
  unbind(el) {
    // set capture to true, on add and remove
    document.body.removeEventListener("click", el.clickOutsideEvent, true);
  }
});




new Vue({
  el: '#vue',
  data: {
    shown: false,
    message: "this is the message for you, click outside the modal"
  },
  methods: {
    hide() {
      this.shown = false;
    }
  },
  components: {

  }
})