I want to play latest audio after page is loaded:
<player ref="player" v-for="item in data"><player>
how can I do something like this:
vm.$refs.player.last().play();
We can access the root Vue instance with $root , and the parent component with $parent . To access a child component from a parent, we can assign a ref with a name to the child component and then use this. $refs to access it.
Accessing the Refs Note that you can only access the ref after the component is mounted. If you try to access $refs.input in a template expression, it will be null on the first render. This is because the element doesn't exist until after the first render!
Emitting Event from Parent to Child We can create a new Vue instance create an event bus and then pass the Vue instance to the child to listen to it. We have the Vue instance in the bus field. Then we can emit the loadMore event to send the event which listens to events from the bus .
create new prop and pass true if the item is the last.
<player ref="player" v-for="(item, index) in data" :should-play="index === data.length - 1">
<player>
player component:
props {
shouldPlay: Boolean
}
mounted() {
if (this.shouldPlay)
this.play();
},
Since the ref is a reference to a regular HTML node, you can access the last child simply by using ParentNode.lastElementChild
.
However, there is one conceptual error in your current code: the same ref is attached to each player instance. You probably meant to attach it to a parent node instead.
new Vue({
el: '#app',
data: {
items: [{
src: "foo"
}, {
src: "bar"
}]
},
mounted() {
const target = this.$refs.parent.lastElementChild
console.log(target)
}
})
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With