鍍金池/ 問(wèn)答/HTML/ vue中數(shù)組會(huì)提示屬性未定義的問(wèn)題

vue中數(shù)組會(huì)提示屬性未定義的問(wèn)題

遇到個(gè)問(wèn)題,就是在vue中,如果數(shù)據(jù)是數(shù)組里面包含對(duì)象,結(jié)構(gòu)如下
data() {

return {
  comment: {},
  commodity: {},
  versions: [
    {
      version: "全網(wǎng)通版 4GB+64GB",
      price: "1599元"
    },
    {
      version: "全網(wǎng)通版 4GB+64GB",
      price: "1599元"
    },
    {
      version: "全網(wǎng)通版 4GB+64GB",
      price: "1599元"
    }
  ]
};

在插值的時(shí)候用{{versions[0].version}}這種形式就會(huì)出警告
[Vue warn]: Error in render: "TypeError: Cannot read property 'version' of undefined"
TypeError: Cannot read property 'version' of undefined
at Proxy.render (eval at ./node_modules/vue-loader/lib/template-compiler/index.js?{"id":"data-v-10009f89","hasScoped":true,"buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/views/Commodity.vue (app.js:1454), <anonymous>:31:51)

但是數(shù)據(jù)能正常渲染出來(lái),就是看到紅字就難受
想知道是什么原因造成的!求大神解惑
回答
編輯回答
凝雅

和 vue 的生命周期有關(guān)。我的理解,在mounted之前數(shù)據(jù)還未準(zhǔn)備好,但是已經(jīng)編譯了模版,所以會(huì)報(bào)錯(cuò)。

更新: 和 vue 的生命周期無(wú)關(guān),是題主的異步數(shù)據(jù)造成的

代碼中可以使用 versions.length && versions[0].version 這樣的方式避免報(bào)錯(cuò)。

2018年4月24日 14:55