此处只展示了大佬的其中一种方法,还有另外两种方法,详情请看:https://www.cnblogs.com/zheroXH/p/11724588.html
第一种方式:最普通的手动监听判断
<span ref="projectButton">
<el-popover v-model="visible" trigger="manual" placement="bottom" @show="show" @hide="hide">
<p>啦啦啦</p>
<el-button slot="reference" type="primary" @click="visible = !visible">show</el-button>
</el-popover>
</span>
data () {
return {
visible: false
}
},
methods: {
show () {
document.addEventListener('click', this.hidePanel, false)
},
hide () {
document.removeEventListener('click', this.hidePanel, false)
},
hidePanel (e) {
if (!this.$refs.projectButton.contains(e.target)) {
this.visible = false
this.hide()
}
}
}
上面就是在 Popover show 的时候监听 document 的 click 事件,触发进入 hidePanel 方法,判断当前点击的 el 是否在 Popover 内部,如果不在,则手动 hide Popover ,并且移除监听事件。
❗❗❗ 注意,ref用在el组件上是没有contains方法的(亲测,用在el-card上就没有),所以如果想用在el组件上就得在外层套一个div,在div上设置ref。