javascript - TypeError:无法读取 v-for 中未定义的属性“0”
问题描述
console.log(this.sights)
返回一个包含 20 个对象的数组,这些对象有几个属性,如name
, photos
,references
等。目前我正在尝试遍历这些对象并显示它们name
的 s 和它们photo_reference
的 s。我这样做:
<div @click='selectSight(index)' v-for='(sight, index) in sights'>
{{ sight.name }}
{{ sight.photos[0].photo_reference }}
</div>
这将显示sight.name
. 但是,我收到一个错误
“渲染错误:”TypeError:无法读取未定义的属性“0””。
我尝试像这样手动访问:
console.log(this.sights[0].photos[0].photo_reference)
它返回photo_reference
. 所以,我没有弄错属性。那么我做错了什么?
这是数组结构:
(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
0:
geometry: Object
icon: "https://maps.gstatic.com/mapfiles/place_api/icons/museum-71.png"
id: "975708e853f136200f2229c793df9070707b842e"
name: "National Museum of Modern Art, Tokyo"
opening_hours: Object
photos: Array(1)
0:
height: 3456
html_attributions: Array(1)
photo_reference: "CmRZAAAA60seVRHbzyg3TPIUPEUaDbzI2-TpMB3cB3bC8BYG_gRrJwmwSVY1Mcl1PBo0U0CMwmqssyQw4w2iHyh6ze3iQaiXdsveolGBovi3rGZTgvKjTV9PRt-WDieYrwoRy1z0EhBsZitey_MyjiwrYK_Sol3eGhSfOpXUpLc-3RYeJjz2JKMMXYNZYw"
width: 4608
解决方案
您收到该错误是因为某些对象具有sight.photos
as undefined
。您可以在访问第零个索引之前添加这样的检查:
<div @click='selectSight(index)' v-for='(sight, index) in sights'>
{{ sight.name }}
{{ sight.photos && sight.photos.length > 0 ? sight.photos[0].photo_reference : '' }}
</div>
推荐阅读
- javascript - 如何在 window.innerheight 中滚动 50% 的视口高度
- node.js - 如何处理 hapi 验证错误?
- gcc - 使用 icc 编译器的答案不正确
- java - 使用 Java 解压缩受密码保护的 zip 文件会引发 NullPointerException
- python - 在numpy中计算相关性
- datatables - Angular 5 ngFor 不适用于 datatables.net
- arrays - 正则表达式:在文本后保留最后一个单词
- css - Firefox上的html2canvas图像问题虽然在chrome上工作正常
- r - 无法使用 R 中的 pROC 库获得正确的多类 ROC 曲线
- html - navbar(menu) 被 body 元素覆盖