vue 手撸下拉框组件 点击页面其他元素会触发隐藏下拉框

实现点击除红色框之外的部分,收缩下拉框

 

 

首先创建一个js文件 clickoutside.js

const clickoutsideContext = '@@clickoutsideContext'

export default {
  bind(el, binding, vnode) {
    const documentHandler = e => {
      if (vnode.context && !el.contains(e.target)) {
        vnode.context[el[clickoutsideContext].methodName]()
      }
    }
    el[clickoutsideContext] = {
      documentHandler,
      methodName: binding.expression,
      arg: binding.arg || 'click'
    }
    document.addEventListener(el[clickoutsideContext].arg, documentHandler)
  },

  update(el, binding) {
    el[clickoutsideContext].methodName = binding.expression
  },

  unbind(el) {
    document.removeEventListener(el[clickoutsideContext].arg, el[clickoutsideContext].documentHandler)
  },

  install(Vue) {
    Vue.directive('clickoutside', {
      bind: this.bind,
      unbind: this.unbind
    })
  }
}
然后使用
在.vue 文件中
1. 引入
import Clickoutside from '@/utils/clickoutside';
2. 引入自定义指令
directives: {
Clickoutside,
},
3.在元素上使用
<div class="tel" v-clickoutside="do">
</div>
methods: {
do() {
  console.log('点击这个元素之外的元素之执行此方法')
}
}
posted @ 2020-10-09 13:59  southPalace  阅读(741)  评论(0编辑  收藏  举报