Vue: Uncaught TypeError: Cannot read property ... from undefined

I use vue@2.1.3 and the official vue web template to create the application.

When developing locally, I often see the Uncaught TypeError: Cannot read property ... of undefined warning, but HTML can be done successfully. However, HTML cannot be displayed when deployed to Netlify using the npm run build . Therefore, I must take this warning seriously.

I learned from here that this is because "the data is not complete when rendering the component, but, for example, it is loaded from the API." and the solution is to "use v-if to display this part of the template only after the data has been downloaded."

There are two questions:

  • I tried wrap v-if around several operators that generate a warning, but personal, I think this solution is detailed. Is there a neat approach?
  • “warnings” in local development turn into “fatal errors” (HTML cannot be visualized) during production. How to make them the same? for example, both of them give warnings or errors?
+5
source share
3 answers

Just use v-if for the common parent to all elements of your template that rely on this AJAX call, and not around each.

So, instead of something like:

 <div> <h1 v-if="foo.title">{{ foo.title }}</h1> <p v-if="foo.description">{{ foo.description }}</p> </div> 

Do

 <div> <template v-if="foo"> <h1>{{ foo.title }}</h1> <p>{{ foo.description }}</p> </template> </div> 
+8
source

Have you tried to initialize all the data you need? for example, if you need a b c , you can do:

 new Vue({ data: { a: 1, b: '', c: {} }, created(){ // send a request to get result, and assign the value to a, b, c here } }) 

This way you will not get xx is undefined error

+1
source

The guys are right, but I can add something. If there is a possibility that your root element in the state might be undefined for any reason, it is recommended to use something like this: v-if='rootElement && rootElement.prop' . This will ensure that you cannot get property prop of undefined , as if rootelement was undefined, it would not continue to check.

+1
source

Source: https://habr.com/ru/post/1261024/


All Articles