Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - How to get last child ref in v-for children components

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();

like image 645
EcoChan Avatar asked Sep 14 '17 11:09

EcoChan


People also ask

How do you access child components at Vue?

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.

How do you access the ref at Vue?

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!

How do you trigger event from parent to child component Vue?

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 .


2 Answers

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();
},
like image 86
Georgi Antonov Avatar answered Oct 17 '22 03:10

Georgi Antonov


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>
like image 42
Etheryte Avatar answered Oct 17 '22 02:10

Etheryte