首页 > 解决方案 > 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

标签: javascriptarraysvue.jsvuejs2

解决方案


您收到该错误是因为某些对象具有sight.photosas 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>

推荐阅读