2016-09-24 156 views
3

js並生成此代碼的彈出窗口,當點擊navbar-link元素時,popover將顯示或隱藏。當我點擊屏幕上的任何地方時(如果彈出窗口打開),關閉popover會更好。Vue.js - 如何跟蹤全局點擊事件

任何想法來實現這一點?

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

預先感謝您:)

回答

9

,您仍然可以使用全局JS功能和事件綁定到文檔元素:有了這個解決方案

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> 
+0

非常感謝!很有幫助! – euvl