我目前正在嘗試使用 Vue 實(shí)作陣列讀?。?/p>
{{ this.locations[this.record.carton.LocationID - 1].Location }}
雖然程式碼本身在運(yùn)行時(shí)運(yùn)作正常,但在首次載入時(shí)會拋出以下錯(cuò)誤:
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: '' }, } } }
解決問題的通用方法是設(shè)定預(yù)設(shè)值或防護(hù)或兩者都設(shè)定。
預(yù)設(shè) - 就像您嘗試過的那樣,除了數(shù)組之外,並注意索引表達(dá)式計(jì)算預(yù)設(shè)索引...
return { data() { return { locations: [{ Location: '' }], record: { carton: { LocationID: 1 } } } } }
但這似乎有點(diǎn)做作且脆弱。另一種方法是使用 v-if 保護(hù)標(biāo)記...
{{ locations[record.carton.LocationID - 1].Location }}
該表達(dá)式涉及的內(nèi)容足以保證將其放入方法中。