click-out-side copy.js 652 Bytes
Newer Older
何虹's avatar
何虹 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

export default {
  bind(el, binding, vnode) {
    el.handler = function(e) {
      if (el.contains(e.target)) {
        return false
      }
      // vnode.context[binding.expression] = false
      binding.value()
    }
    el.stopProp = function(event) {
      event.stopPropagation()
    }
    el.addEventListener('click', el.stopProp)
    document.body.addEventListener('click', el.handler)
  },
  unbind(el, binding) {
    el.removeEventListener('click', el.stopProp)
    document.body.removeEventListener('click', el.handler)
  },
  install(Vue) {
    Vue.directive('clickoutside', {
      bind: this.bind,
      unbind: this.unbind
    })
  }
}