Skip to content
Advertisement

Can’t get id of a dynamically added component with v-for

I have a v-for loop that populates <audio> components backed by an array of blobs and the buttons to play and delete it.

<div v-for="(file, index) in soundFiles" :key="index">
  <audio :src="file.url" :id="file.uuid" :ref="el => audios[file.uuid] = el" />{{ file.name }}&nbsp;
  <button :id="file.uuid" v-on:click="playSound">&gt;</button>
  <button :id="file.uuid" v-on:click="deleteSound">X</button>
</div>

The way :ref is used is taken from this example

const soundFiles = ref([]);
const audios = ref([]);
//......
function playSound(e) {
  const soundId = e.target.id;
  audios.value[soundId].play();
}

When I add a sound and then click the play button I get an empty soundId. The inspector also shows that the audio and buttons don’t have any attributes. When I reload the page the data is pulled from the local storage, the underlying array for v-for is populated in the setup() function and the elements are created with attributes just fine. What should I do to set the ids of my elements dynamically?

Advertisement

Answer

<div v-for="(file, index) in soundFiles" :key="index">
  <audio :src="file.url" :id="file.uuid" :ref="el => audios[file.uuid] = el" />{{ file.name }}&nbsp;
  <button :id="file.uuid" v-on:click="playSound(file.uuid)">&gt;</button>
  <button :id="file.uuid" v-on:click="deleteSound">X</button>
</div>
function playSound(id) {
  audios.value[id].play();
}

Why don’t you write it like that?

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement