【问题标题】:Vue JS: Open Menu Component with Button, Close with Click Outside of MenuVue JS:用按钮打开菜单组件,在菜单外点击关闭
【发布时间】: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

//--- 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


    【解决方案1】:

    试试这个

    ...
    methods:{
      clickYears: function(event){
        this.$refs.Years.show = true
        event.stopPropagation();
      }
    }
    ...
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2022-08-10
    • 1970-01-01
    • 2018-09-29
    • 2012-08-29
    • 2019-12-09
    • 1970-01-01
    相关资源
    最近更新 更多