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('点击这个元素之外的元素之执行此方法')
}
}
}