本文介绍了在窗口上添加 Vue.js 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vue.js 允许在元素上应用事件:

<button @click="play()">播放</button>

但是如何在 window 对象上应用事件?它不在 DOM 中.

例如:

<div @mousedown="startDrag()" @mousemove="move($event)">拖拽我</div>

在这个例子中,如何监听 window 上的 mousemove 事件?

解决方案

你应该在组件的创建和销毁过程中手动进行

...创建:函数(){window.addEventListener('mousemove',this.move);},销毁:函数(){window.removeEventListener('mousemove', this.move);}...

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 ?

解决方案

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

这篇关于在窗口上添加 Vue.js 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:09