Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Vue.js event on window

Vue.js allow apply event on element:

<div id="app">    <button @click="play()">Play</button> </div> 

But how to apply event on window object? it is not in DOM.

for example:

<div id="app">   <div @mousedown="startDrag()" @mousemove="move($event)">Drag me</div> </div> 

in this example, how to listen mousemove event on window ?

like image 348
Yukulélé Avatar asked May 03 '16 00:05

Yukulélé


People also ask

How do I add an event to Vue?

We add an argument to the v-on directive, which will be the name of the event we want to handle. In the above example case, it is a click event. After that, we have to bind an expression to the directive, which will normally be a method you want to use to handle the event. In this case, we've called it clickHandler.

Can you add event listener to window?

You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.

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 listen to the window scroll event in a Vuejs component?

We can listen to the window scroll event in a Vue. js component by calling the window. addEventListener method to listen to the scroll event on the browser window. We call window.


1 Answers

You should just do it manually during the creation and destruction of the component

... created: function() {   window.addEventListener('mousemove',this.move); }, destroyed: function() {   window.removeEventListener('mousemove', this.move); } ... 
like image 56
Jeff Avatar answered Oct 05 '22 12:10

Jeff