Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
918 views
in Technique[技术] by (71.8m points)

vue.js - Vue warning when accessing nested object

I am not sure why I get a Vue warning when accessing nested object.

{{ user.area.name }}

[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"

TypeError: Cannot read property 'name' of undefined

Just accessing the object has no warning.

{{ user.name }}

Any advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Totally guessing here but lets see if I'm right...

Say you've got something like this in your component / Vue instance data initialiser...

data () {
  return {
    user: {}
  }
}

and you then populate that object asynchronously, eg

mounted () {
  setTimeout(() => { // setTimeout is just an example
    this.user = {
      ...this.user,
      area: {
        name: 'foo'
      }
    }
  }, 1000)
}

If your template has

{{ user.area.name }}

when it initially renders before the asynchronous task has completed, you will be attempting to access the name property of area which is undefined.

Example ~ http://jsfiddle.net/tL1xbmoj/


Your options are...

  1. Initialise your data with a structure that won't cause errors

    data () {
      return {
        user: {
          area: { 
            name: null 
          } 
        }
      }
    }
    

    Example ~ http://jsfiddle.net/tL1xbmoj/1/

  2. Use conditional rendering to prevent the error

    <span v-if="user.area">{{ user.area.name }}</span>
    

    Example ~ http://jsfiddle.net/tL1xbmoj/2/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...