【发布时间】:2019-10-07 07:25:29
【问题描述】:
Vue JS 2.6.10
我已经阅读了各种关于如何创建自定义指令的 SO 帖子,以便您可以检测到弹出菜单之外的点击,以便关闭它。我不能让它工作,因为我有一个打开菜单的按钮,点击它会触发“关闭”行为。
这是我的主视图 Logbook.vue,其中包含打开菜单的按钮:
// --- Logbook.vue ---
<script>
export default {
name: 'Logbook',
components:{
Years
},
methods:{
clickYears: function(){
this.$refs.Years.show = true
}
}
}
</script>
<template>
<div id="current-year">
<a href="#year" ref="yearButton" v-on:click.prevent="clickYears">{{ currentYear }}</a>
<Years ref="Years" v-on:selectYear="yearSelected" />
</div>
</template>
//--- Years.vue ---
<script>
import Vue from 'vue'
//Custom directive to handle clicks outside of this component
Vue.directive('click-outside', {
bind: function (el, binding, vnode) {
window.event = function (event) {
if (!(el == event.target || el.contains(event.target))) {
vnode.context[binding.expression](event)
}
};
document.body.addEventListener('click', window.event)
},
unbind: function (el) {
document.body.removeEventListener('click', window.event)
}
})
export default{
name: 'Years',
data() {
return {
show: false
}
},
methods:{
close: function(){
this.show = false
}
}
}
</script>
<template>
<div id="years" v-show="show" v-click-outside="close">
<!-- Years listed here... -->
</div>
</template>
当我在Years 组件外部单击时,close 方法会正确触发,但问题是我一开始就无法打开Years 菜单,因为单击按钮也 触发 close 行为,因为它也在 Years 组件之外。
有人克服过这个问题吗?有什么想法吗?
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component custom-directive