vue自定义指令clickoutside实现点击其他元素才会触发

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 @ 2019-07-17 11:31  love星期六  阅读(3450)  评论(0编辑  收藏  举报