<template>
<div v-clickoutside="clickItemOut"></div>
</template>
const clickoutside = {
bind (el, binding, vnode) {
function documentHandler (e) {
if (el.contains(e.target)) {
return false
}
if (binding.expression) {
binding.value(e)
}
}
el.__vueClickOutside__ = documentHandler
document.addEventListener('click', documentHandler)
},
unbind (el, binding) {
document.removeEventListener('click', el.__vueClickOutside__)
delete el.__vueClickOutside__
}
}
组件中声明自定义指令(全局也可以,改写成全局各式就好了)
directives: { clickoutside }
methods: {
clickItemOut (e) {
// 点击元素之外触发函数
}