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 }}
<button :id="file.uuid" v-on:click="playSound">></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 }}
<button :id="file.uuid" v-on:click="playSound(file.uuid)">></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?