But...">

Add Vue.js event to window

Vue.js allows you to apply an event to an element:

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

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

eg:

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

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

+8
javascript javascript-events
source share
4 answers

You must simply do this manually during component creation and destruction.

 ... created: function() { window.addEventListener('mousemove',this.move); }, destroyed: function() { window.removeEventListener('mousemove', this.move); } ... 
+22
source share

You can also use the vue-global-events library.

 <GlobalEvents @mousemove="move"/> 

It also supports event modifiers such as @keydown.up.ctrl.prevent="handler" .

+1
source share

Jeff's answer is perfect and should be an accepted answer. They helped me a lot!

Although I have something to add, which caused me a headache. When defining the move method, it is important to use the function constructor and not use the ES6 arrow functions if you want to access this on a child component. this not passed to arrow functions.

Here is my implementation with the called method enabled (here it is called keyDown instead of move ):

 export default { name: 'app', components: { SudokuBoard }, methods: { keyDown: function () { const activeElement = document.getElementsByClassName('active')[0] if (activeElement && !isNaN(event.key) && event.key > 0) { activeElement.innerHTML = event.key } } }, created: function () { window.addEventListener('keydown', this.keyDown) }, destroyed: function () { window.removeEventListener('keydown', this.keyDown) } } 

To be more clear, the method below does not have access to this and cannot, for example, reach a data or property object on your child component.

 methods: { keyDown: () => { //no 'this' passed. Can't access child context } 
+1
source share

This is for anyone who has landed here looking for a solution for nuxt.js :

I created a sticky title for one of my projects and ran into a problem to get window.addEventListener to work.

First of all, I'm not sure why, but window.addEventListener does not work with created or beforeCreate , so I use mounted .

 <template lang="pug"> header(:class="{ 'fixed-header': scrolled }") nav menu here </template> <script> export default { name: 'AppHeader', data() { return { scrolled: false }; }, mounted() { // Note: do not add parentheses () for this.handleScroll window.addEventListener('scroll', this.handleScroll); }, methods: { handleScroll() { this.scrolled = window.scrollY > 50; }, }, }; </script> 
0
source share

All Articles