Vuejs 监听器
Vuejs listeners
我正在创建简单的应用程序,它的听众很少。我不知道这背后的逻辑应该是什么样子。
HTML:
<div id="playerProgressBar">
<div id="playerHead"></div>
</div>
在 Vue 对象中我定义了变量:
music: document.getElementById('playerHead');
我的听众应该是这样的:
music.addEventListener("timeupdate", timeUpdate, false);
music.addEventListener("canplaythrough", function () {
//code
}, false);
function timeUpdate() {
//code
}
那么在 vuejs 中使用监听器的正确方法是什么?我应该在这里使用自定义指令吗?因为我没有事件,所以我不能使用方法。将整个逻辑放在 ready
函数中似乎不是正确的方法。提前致谢!
这将是将 HTML 元素分配给应用程序的 Vue-esque 方式:
<video v-el:video-element controls>
<source src="mov_bbb.mp4" type="video/mp4">
</video>
这已解析为应用中的一个变量 this.$els.videoElement
。更多信息 here.
现在,要为它们添加侦听器和函数,我会这样做:
...
ready: function() {
this.addListeners();
},
methods: {
addListeners: function() {
console.log('adding listeners');
this.$els.videoElement.addEventListener('timeupdate',this.videoTimeUpdated,false);
},
videoTimeUpdated: function() {
console.log('video time updated');
}
}
...
显然,您可以将所有视频(或任何其他与事件相关的)内容放在单独的 component 中(在 Vue 中不是指令)以使代码更整洁。
v-on (shorthand: @)
When used on a normal element, it listens to native DOM events only. When used on a custom element component, it also listens to custom events emitted on that child component.
因此,您可以像这样附加一个事件侦听器:
<video @timeupdate="onTimeUpdateListener" src="..."></video>
这是我使用 MediaElement 库的示例:
https://jsfiddle.net/248nqk02/
我正在创建简单的应用程序,它的听众很少。我不知道这背后的逻辑应该是什么样子。
HTML:
<div id="playerProgressBar">
<div id="playerHead"></div>
</div>
在 Vue 对象中我定义了变量:
music: document.getElementById('playerHead');
我的听众应该是这样的:
music.addEventListener("timeupdate", timeUpdate, false);
music.addEventListener("canplaythrough", function () {
//code
}, false);
function timeUpdate() {
//code
}
那么在 vuejs 中使用监听器的正确方法是什么?我应该在这里使用自定义指令吗?因为我没有事件,所以我不能使用方法。将整个逻辑放在 ready
函数中似乎不是正确的方法。提前致谢!
这将是将 HTML 元素分配给应用程序的 Vue-esque 方式:
<video v-el:video-element controls>
<source src="mov_bbb.mp4" type="video/mp4">
</video>
这已解析为应用中的一个变量 this.$els.videoElement
。更多信息 here.
现在,要为它们添加侦听器和函数,我会这样做:
...
ready: function() {
this.addListeners();
},
methods: {
addListeners: function() {
console.log('adding listeners');
this.$els.videoElement.addEventListener('timeupdate',this.videoTimeUpdated,false);
},
videoTimeUpdated: function() {
console.log('video time updated');
}
}
...
显然,您可以将所有视频(或任何其他与事件相关的)内容放在单独的 component 中(在 Vue 中不是指令)以使代码更整洁。
v-on (shorthand: @)
When used on a normal element, it listens to native DOM events only. When used on a custom element component, it also listens to custom events emitted on that child component.
因此,您可以像这样附加一个事件侦听器:
<video @timeupdate="onTimeUpdateListener" src="..."></video>
这是我使用 MediaElement 库的示例: https://jsfiddle.net/248nqk02/