我希望在加载页面后播放最新音频:
<player ref="player" v-for="item in data"><player>
我该怎么做:
vm.$refs.player.last().play();
答案 0 :(得分:4)
创建新道具,如果项目是最后一个,则传递true。
<player ref="player" v-for="(item, index) in data" :should-play="index === data.length - 1">
<player>
播放器组件:
props {
shouldPlay: Boolean
}
mounted() {
if (this.shouldPlay)
this.play();
},
答案 1 :(得分:2)
由于ref是对常规HTML节点的引用,因此您只需使用ParentNode.lastElementChild
即可访问最后一个子节点。
但是,当前代码中存在一个概念错误:每个播放器实例都附加了相同的引用。您可能希望将其附加到父节点。
new Vue({
el: '#app',
data: {
items: [{
src: "foo"
}, {
src: "bar"
}]
},
mounted() {
const target = this.$refs.parent.lastElementChild
console.log(target)
}
})
&#13;
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div ref="parent">
<player v-for="(item, index) in items" v-bind:key="index" v-bind:src="item.src"></player>
</div>
</div>
&#13;