一个对象有一些属性,其中 6 个属性称为 item0、item1、item2、item3、item4 和 item5
。我想使用 URL 中的这些属性值和我看到的方式来渲染 6 个图像,我可以复制图像元素 6 次,然后只更改项目编号,如下所示:
<img v-if='match.mainParticipant.stats.item0' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/item/' + match.mainParticipant.stats.item0 + '.png'" alt="">
<img v-if='match.mainParticipant.stats.item1' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/item/' + match.mainParticipant.stats.item1 + '.png'" alt="">
<img v-if='match.mainParticipant.stats.item2' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/item/' + match.mainParticipant.stats.item2 + '.png'" alt="">
<img v-if='match.mainParticipant.stats.item3' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/item/' + match.mainParticipant.stats.item3 + '.png'" alt="">
<img v-if='match.mainParticipant.stats.item4' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/item/' + match.mainParticipant.stats.item4 + '.png'" alt="">
<img v-if='match.mainParticipant.stats.item5' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/item/' + match.mainParticipant.stats.item5 + '.png'" alt="">
或者我可以创建一个 v-for 循环并循环遍历数字 0-5,如下所示:
<img v-for="i in 6" :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/item/' + match.mainParticipant.stats.item + (i - 1) + '.png'" alt="">
您可能会注意到我正在循环 1-6,但这是因为 v-for 循环出于某种原因从 1 开始。这就是我后来减1的原因。遗憾的是,由于某种原因,此代码无法成功获取图像,并且在控制台中我收到错误:
GET http://ddragon.leagueoflegends.com/cdn/9.16.1/img/item/undefined4.png 403 (Forbidden)
显然,undefined4 应该是 item4,这样才能正常工作,但我不明白为什么 URL 会变成这样。
最佳答案
在您访问名为 match.mainParticipant.stats.item
的属性时的编写方式,该属性将是未定义
。然后,您可以在该值的末尾添加一个数字,从而得到 undefined4
等。
您需要使用方括号来动态访问属性。
所以:
match.mainParticipant.stats['item' + (i - 1)]
或带反引号:
match.mainParticipant.stats[`item${i - 1}`]
关于javascript - 尝试使用 v-for 循环和对象属性动态创建 URL,但收到 GET 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57555417/