Vue JS:使用按钮打开菜单组件,通过单击菜单外部关闭

Cli*_*rum 1 javascript vue.js vue-component vuejs2 custom-directive

Vue JS 2.6.10

我读过很多关于如何创建自定义指令的帖子,以便您可以检测到弹出菜单外部的单击,以便可以将其关闭。我无法完全让它工作,因为我有一个打开菜单的按钮,单击它会触发“关闭”行为。

这是我的主视图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>
Run Code Online (Sandbox Code Playgroud)

Years.vue以下是单击按钮时打开的 菜单组件:在此输入图像描述

//--- 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>
Run Code Online (Sandbox Code Playgroud)

close当我单击组件外部时,该方法会正确触发Years,但问题是我无法从一开始就打开菜单,Years因为单击按钮也会触发该close行为,因为它Years 组件之外。

有人克服了这个问题吗?有任何想法吗?

Mil*_*han 5

尝试这个

...
methods:{
  clickYears: function(event){
    this.$refs.Years.show = true
    event.stopPropagation();
  }
}
...
Run Code Online (Sandbox Code Playgroud)