首頁  >  問答  >  主體

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: ''
            },
        }
     }
 }

P粉955063662P粉955063662199 天前377

全部回覆(1)我來回復

  • P粉094351878

    P粉0943518782024-04-04 11:16:41

    解決問題的通用方法是設定預設值或防護或兩者都設定。

    預設 - 就像您嘗試過的那樣,除了數組之外,並注意索引表達式計算預設索引...

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

    但這似乎有點做作且脆弱。另一種方法是使用 v-if 保護標記...

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

    該表達式涉及的內容足以保證將其放入方法中。

    回覆
    0
  • 取消回覆