无法使用 v-for 获取动态添加的组件的 ID

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

我有一个 v-for 循环,它填充 <audio> 由一组 blob 和用于播放和删除它的按钮支持的组件。

<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>

:ref的使用方式取自this example

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

当我添加声音然后单击播放按钮时,我得到一个空的 soundId。检查器还显示音频和按钮没有任何属性。当我重新加载页面时,数据从本地存储中提取,v-for 的底层数组被填充到 setup() 函数中,并且元素是用属性创建的。 我应该怎么做才能动态设置元素的 ID?

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

为什么不这样写呢?

如果动态添加任何内容,请不要使用索引作为 v-for 键,创建键 ID。如果您的数据没有默认 id,请在计算 属性:

中动态添加它
<div v-for="file in files" :key="file.id"></div>

data() {
  return {
    soundFiles: [ array of your files ],
  }
},
computed: {
  files() {
    return soundFiles.map(x => {
      x.id = Math.floor(Math.random() * 1000000000)
      return x;
    })
  }
}