繁体   English   中英

Vue.js - 如何跟踪全局点击事件

[英]Vue.js - How to track global click event

js并生成了popover的这段代码,当点击navbar-link元素时,将显示或隐藏popover 什么是好的是当我点击屏幕上的任何地方时关闭popover (如果popover打开)。

有什么想法可以实现吗?

<template>
  <div>
    <span class="navbar-link" v-on:click="toggle()">
      <i class="ion-android-notifications-none"></i>
    </span>
    <div class="popover" v-bind:class="{ 'open': opened }">
      Hello, world!
    </div>
  </div>
</template>
<script>
  export default{
    data(){
      return {
        opened: false
      }
    },
    methods: {
      toggle: function () {
        this.opened = !this.opened;
      }
    }
  }
</script>

先感谢您 :)

您仍然可以使用全局js函数并将事件绑定到document元素:

export default {
    data () {
        return {
            opened: false
        }
    },
    methods: {
        toggle () {
            if (this.opened) {
                return this.hide()
            }
            return this.show()
        },
        show () {
            this.opened = true;
            setTimeout(() => document.addEventListener('click',this.hide), 0);
        },
        hide () {
            this.opened = false;
            document.removeEventListener('click',this.hide);
        }
    }
}

使用此解决方案,单击弹出窗口也将关闭它。 所以你需要停止在你的popover上传播点击事件:

<div class="popover" v-bind:class="{ 'open': opened }" @click.stop>
    Hello, world!
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM