如何在vue中初始化一个数组子元素

How to initialize an array subelement in vue

我目前正在尝试使用 Vue 实现数组读取:

{{ this.locations[this.record.carton.LocationID - 1].Location }}

虽然代码本身在 运行 时间内运行良好,但在首次加载时抛出以下错误:

app.js:55125 [Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'Location')"

app.js:56401 TypeError: Cannot read properties of undefined (reading 'Location')
    at Proxy.render (app.js:49569:28)
    at VueComponent.Vue._render (app.js:58068:22)
    at VueComponent.updateComponent (app.js:58580:21)
    at Watcher.get (app.js:58994:25)
    at new Watcher (app.js:58983:12)
    at mountComponent (app.js:58587:3)
    at VueComponent.Vue.$mount (app.js:63593:10)
    at VueComponent.Vue.$mount (app.js:66507:16)
    at init (app.js:57639:13)
    at merged (app.js:57824:5)

我试过像这样初始化 Location 的值,但似乎没有帮助

return {
     data() {
        return {
            locations: {
                Location: ''
            },
        }
     }
 }

解决问题的通用方法是设置默认值或守卫或两者。

默认值 - 与您尝试的一样,除了使用数组,并注意索引表达式计算出默认索引...

return {
   data() {
      return {
        locations: [{ Location: '' }],
        record: { carton: { LocationID: 1 } }
      }
   }
 }

但这似乎有点做作和脆弱。另一种方法是使用 v-if...

来保护标记
<div v-if="record && record.carton && locations && record.carton.LocationID - 1 < locations.length">
  {{ locations[record.carton.LocationID - 1].Location }}
</div>

该表达式足够复杂,足以保证将它放在一个方法中。