我目前正在尝试使用 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>
该表达式涉及的内容足以保证将其放入方法中。
关于javascript - vue中如何初始化数组子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71946776/