Vue warning when accessing nested object

落爺英雄遲暮 提交于 2019-12-20 07:46:22

问题


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?


回答1:


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/




回答2:


Your user doesn't contain an area, so when you try to read that, it's undefined. You're not allowed to use the . operator on things that are undefined, so when you do .name on that, you get the error that you got.



来源:https://stackoverflow.com/questions/52751705/vue-warning-when-accessing-nested-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!