Vue.js 是我的第一个响应式库,我在处理方法和子元素时遇到了问题。我怀疑我遗漏了一些明显的东西。
在我的示例中,呈现的列表项具有悬停(mouseenter 和 mouseleave)事件的方法处理程序。每个列表项都是 <video>
的父级元素,默认暂停。当鼠标进入一个列表项时,它的 child <video>
播放 (elem.play())。当鼠标离开列表项时视频暂停。
完整示例:https://jsfiddle.net/matbergman/hcgtkbwt/8/
<ul class="contentList">
<li v-for="item in items" v-on:mouseover="videoPlay()" v-on:mouseleave="videoPause()">
<video loop="loop" v-bind:src="item.video"></video>
<p>
{{item.description}}
</p>
</li>
</ul>
<script>
var vm = new Vue ({
el: ".contentList",
data: {
items: [
{
video : "http://206.130.101.116/misc/video01.mp4",
description : "Video 1"
},
{
video : "http://206.130.101.116/misc/video02.mp4",
description : "Video 2"
},
{
video : "http://206.130.101.116/misc/video03.mp4",
description : "Video 3"
}
]
},
methods: {
videoPlay: function() {
console.log("play");
vm.$el === document.getElementById('example')
// Play the child video, something like: this.getElementsByTagName("video")[0].play();
},
videoPause: function() {
console.log("pause");
// Pause the child video, something like: this.getElementsByTagName("video")[0].pause();
}
}
});
</script>
我的方法识别鼠标事件。我如何将 play() 方法应用于 child <video>
?在 jQuery 中它会是这样的:
$("li").mouseenter(function() {
this.getElementsByTagName("video")[0].play();
});
但是范围this
当然是由我的 $el 变量定义的,而不是像我习惯的带有附加事件的元素。 play() 方法会以某种方式作为组件的属性传递吗?
最佳答案
Vue 允许您访问事件对象。
当您仅提供方法名称时,它会隐式传递:
<div @click="clickHandler">
... 或者可以使用 $event
变量显式传递:
<div @click="clickHandler($event)">
您可以使用事件的目标来访问触发事件的元素。从那里,您可以按照您的描述访问其子项。下面是一个使用 mouseenter 和 mouseleave 的例子:
new Vue ({
el: ".contentList",
methods: {
videoPlay: function(event) {
document.getElementById("consolelog").innerText = "play";
event.currentTarget.getElementsByTagName("video")[0].play();
},
videoPause: function(event) {
document.getElementById("consolelog").innerText = "pause";
event.currentTarget.getElementsByTagName("video")[0].pause();
}
}
});
li {
list-style:none;
padding:1em;
margin:2em;
background-color:#f1f1f1;
}
li:hover {
background-color:#ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script>
<ul class="contentList">
<li @mouseenter="videoPlay" @mouseleave="videoPause">
<video loop="loop" src=""></video>
</li>
</ul>
<div id="consolelog" style="position:fixed; top:10px; right:10px; background-color:#ffffcc; padding:5px;">
</div>
关于Vue.js 中的 JavaScript 方法和子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38363624/