[Solved] TypeError Cannot read property ‘xxx’ of undefined error analysis

This sentence literally translates to: TypeError: Cannot read property ‘xxx’ of undefined

First go to see if the attribute ‘xxx’ is defined. If it is not defined, define it in the data or method according to the actual needs.

  1. If it is defined in data, first check if your data is written correctly. I mistakenly typed the date once, and it took an afternoon to see it o(╥﹏╥)o

  2. If the data “xxx” is obtained asynchronously from the background, it is best to give him a default value in the data. For

data()  { 
   return  { 
      obj1:  '' , 
      obj2:  null .
       obj3:  {}, 
      obj4:  [] 
    //  Get background data and assign values ​​to objs and other asynchronous operations 

or when “xxx” is a struct obj.name [nested two levels deep]

data() {
   return {
      obj: {
        name: '',
        age: null,

However, when “xxx” is a multi-level nested structure obj.name.firstName, or the structure is very complex, it is not recommended to use this “placeholder” method. You can use the v-if command in the template to determine whether the value exists . For

  <div>{{ obj.name.firstName}}</div>
  <div>{{ obj.age}}</div>

// good
  <div v-if="foo.name && foo.title.firstName">{{ age.name.firstName}}</div>
  <div v-if="foo.age">{{ age.age}}</div>

Note to use v-if, not v-show

When the page is initialized, the data is taken from the data. You have not defined it in the data, so he must not report an error. And because the execution of the program is very fast, after getting the data assignment and triggering the page update, it can be displayed. This is why sometimes this error is reported, but the value of “xxx” can still be displayed on the page.

Leave a Comment

Your email address will not be published. Required fields are marked *