javascript - 尝试使用 v-for 循环和对象属性动态创建 URL,但收到 GET 错误

标签 javascript vue.js vuejs2

一个对象有一些属性,其中 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/

相关文章:

php - 数据库保存和检索最后保存的值

javascript - 使用 AJAX 和 PHP 登录时获取用户配置文件

javascript - 如何在 v-for 循环中仅打印第一个获胜者?

typescript - Vuex Typescript 我收到错误 "Member ' someMutation' implicitly has an 'any' type."in the Component.ts file

vue.js - Vue2 + Vuex - 不渲染在存储中成功设置的数组

javascript - npm 在../../node_modules 而不是/node_modules 中安装包,为什么?

javascript - 删除列后使 IE8 重新呈现表格

vue.js - Vitest 与 Quasar 的集成

javascript - 我无法将我的 Vuejs 应用连接到 Firebase

javascript - Vue.js - 将类添加到单击的按钮