Reputation: 149
I have this code in my Vue2 app. It's from a vuetify data table and is to insert the chapter name belonging to the item.chapterId
<template v-slot:item.chapter="{ item }">
{{ chapters.find(x => x.id === item.chapterId).locale.en.title }}
</template>
It works fine but gives a warning error:
[Vue warn]: Error in render: "TypeError: Cannot read property 'locale' of undefined"
I'm new to Vue but think it would be better off as a computed property to take advantage of caching. How can I get rid of the warning and or improve the code?
Upvotes: 1
Views: 732
Reputation: 973
Another way of doing it would be
<template v-slot:item.chapter="{ item }">
{{ chapters.length > 0 ? chapters.find(x => x.id === item.chapterId).locale.en.title : '' }}
</template>
Upvotes: 0
Reputation: 3420
The problem is that locale
prop does not exist, this error is probably raising at first render, when chapters is still not populated with data.
This is a common problem when loading data from an API, because first DOM render happens before all data is fetched and so you are seeing this error cause locale property does not exist yet.
An easy solution is to add an v-if="chapters.length"
so the template gets rendered only when chapters
is populated.
This should solve it:
<template v-if="chapters.length" v-slot:item.chapter="{ item }">
{{ chapters.find(x => x.id === item.chapterId).locale.en.title }}
</template>
controlling when the data is loaded and only render the templates related to this data when it is actually available is a good practice.
Computed properties are not a solution for this as it requires a parameter item
to be passed in order to be able to do the match.
Upvotes: 1