简体   繁体   中英

Vue.js - How to track global click event

js and produced this code of the popover, when clicking on the navbar-link element, popover will be shown or hidden. What would be nice is to close popover when I click anywhere on the screen (if popover is open).

Any ideas to accomplish that?

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

Thank you in advance :)

You can still use global js functions and bind events to the document element:

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);
        }
    }
}

With this solution, a click on the popover will also close it. So you need to stop propagation of clicks events on your popover:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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