title: Conditionally bind custom-directives in vue js for 'clicking outside an element event'
body: <p>References </p>
  
  <p><a href="https://stackoverflow.com/questions/37526888/add-vue-directive-on-condition">Add vue directive on condition</a></p>
  
  <p><a href="https://stackoverflow.com/questions/36170425/detect-click-outside-element">Detect click outside element</a></p>
  
  <p>I am writing a custom directive for 'click-outside senario' for a list of elements.</p>
  
  <p>Basically when a button is clicked on a item in the list it goes into selected mode . Now if a click occurs anywhere else I need to cancel selection mode .
  For that I need to detect click outside . 
  I figured out the directive for it from 
  For that I have come up with </p>
  
  <pre><code>  const clickOutside = {
    bind: function (el, binding, vnode) {
      console.log('bind called')
  
      document.body.addEventListener('click', (event) =&gt; {
        // check that click was outside the el and his childrens
        if (!(el == event.target || el.contains(event.target))) {
          // and if it did, call handle method provided in attribute value
          console.log('directive working')
          vnode.context[binding.expression](event);
        }
      })
    },
    unbind: function (el) {
      document.body.removeEventListener('click', el.event)
      console.log('unbind called')
    }
  }
  export {
    clickOutside
  }
  </code></pre>
  
  <p>from the reference sited above </p>
  
  <p>Now I only want each list item to listen for outside clicks when that item is in selected mode . </p>
  
  <p>So I need to accomplish something like</p>
  
  <pre><code>&lt;div id="list-item"  v-on-click-outside="outSideClickHandler" //trigger only when selected&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
  export default{
  data:{
  selectedState:false;
  },
  methods:{
  outSideClickHandler:{//......}
  }
  &lt;/script&gt;
  </code></pre>