Vue warning when accessing nested object

后端 未结 2 1572
清酒与你
清酒与你 2021-01-17 05:36

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

{{ user.area.name }}

[Vue warn]: Error in render: \"Type

2条回答
  •  春和景丽
    2021-01-17 06:23

    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

      {{ user.area.name }}
      

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

提交回复
热议问题