我有一个组件正在安装在 v-for 循环上。挂载的组件有一个 onMount 方法。该方法执行一些代码来获取我在 firebase 中找到的 img url,并使用该 url 设置 img src。我的组件安装了 3 次,代码执行了 3 次,但只有一张图像的 src 得到更新。它每次都会使用随机 URL 进行更新。如果我在 firebase 中有 3 个图像,则在每一页上刷新 img 的 src 更改为新的 url,即使它应该有一个正确的 url。行为应该是每个组件的图像 src 都使用正确的图像进行更新。如有任何帮助,我们将不胜感激。
元件安装:
<div :key="expert.email" v-for="expert in filteredExperts">
<ExpertCard @openPopup="openPopup" :Expert="expert" class=""/>
</div>
组件挂载方法:
onMounted(async () => {
const storage = getStorage();
const ImgRef = Ref(storage, props.Expert.profile_picture);
await getDownloadURL(ImgRef)
.then((url) => {
// Or inserted into an <img> element
console.log(url)
const img = document.getElementById('myimg');
img.setAttribute('src', url);
})
.catch((error) => {
// Handle any errors
});
})
图片来源:
<img id="myimg" class="mx-auto rounded w-24 h-24" src="">
我假设您需要选择是使用
await
还是 then
试试这个(我删除了异步/等待):
onMounted(() => {
const storage = getStorage();
const ImgRef = Ref(storage, props.Expert.profile_picture);
getDownloadURL(ImgRef)
.then((url) => {
// Or inserted into an <img> element
console.log(url)
const img = document.getElementById('myimg');
img.setAttribute('src', url);
})
.catch((error) => {
// Handle any errors
});
})
PS:我建议你用这个替换 document.getElementById 等:
<img :src="profilePicture" >
<script setup>
const profilePicture = ref(null)
...
console.log(url)
profilePicture.value = url;
...
</script>