Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js + Call the click event for whole page document

With JQuery, click event of the any item in the page can be captured as below.

$(document).click(function(event){
     // event.target is the clicked element object
});

How to do the same with Vue.js?

like image 921
asankasri Avatar asked Jan 31 '17 05:01

asankasri


People also ask

What is @input in VUE JS?

It provides two-way data binding by binding the input text element and the value binded to a variable assigned.

How do you call an event listener only once?

We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.

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

What is the shorthand way to invoke a function when a click event is fired?

v-on will trigger the expression or the method specified when the click event in triggered on the button element.


1 Answers

The answer provided by M U is correct and works.

Yet if you don't like messing with your template (e.g. not put a lot of event handlers in it) or your Vue app is only a small part of a bigger application, it's also perfectly fine and acceptable to register event handlers manually.

To add global event handlers in your script the Vue way you should register them in the mounted and remove them in the beforeDestroy hooks.

Short example:

var app = new Vue({
  el: '#app',
  mounted: function () {
    // Attach event listener to the root vue element
    this.$el.addEventListener('click', this.onClick)
    // Or if you want to affect everything
    // document.addEventListener('click', this.onClick)
  },
  beforeDestroy: function () {
    this.$el.removeEventListener('click', this.onClick)
    // document.removeEventListener('click', this.onClick)
  },
  methods: {
    onClick: function (ev) {
      console.log(ev.offsetX, ev.offsetY)
    }
  }
})
like image 121
Bengt Avatar answered Sep 20 '22 07:09

Bengt