Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 336
euvl Avatar asked Sep 24 '16 09:09

euvl


People also ask

How do I listen to the Vue events?

Listening to Events We can use the v-on directive, which we typically shorten to the @ symbol, to listen to DOM events and run some JavaScript when they're triggered. The usage would be v-on:click="handler" or with the shortcut, @click="handler" .

How do I check my Vue app performance?

Then use the “Performance tab” to measure your Vue app's performance. Press start and stop to run a performance check, ideally during the app load. And then go to the “Component Render” tab. If your page renders 100 components, then you should see 100 created events.

Does Vue follow MVC?

The name of the framework – Vue – is the same phonetically in English as view, and it corresponds to the traditional Model-View-Controller (MVC) architecture. Simply put, a view is a UI of an application/website, and the core library of Vue. js focuses on the view layer by default.


1 Answers

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>
like image 173
Hammerbot Avatar answered Nov 26 '22 07:11

Hammerbot