How to initialize the sub-elements of an array in Vue
P粉955063662
P粉955063662 2024-04-03 13:24:48
0
1
450

I'm currently trying to use Vue to implement array reading:

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

While the code itself works fine at runtime, on first load it throws the following error:

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)

I tried initializing the value of Location like this but it doesn't seem to help

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

P粉955063662
P粉955063662

reply all(1)
P粉094351878

The general way to solve the problem is to set defaults or guards or both.

Default - Just like you tried, except for arrays, and note that the index expression calculates the default index...

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

But this seems a bit contrived and flimsy. Another way is to use v-if to protect the tag...

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

The expression involves enough content to warrant putting it into a method.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template