Reputation: 707
I'm working on a Vue project where, at one point, I need to display data from the store (I use Vuex) in the template. The data I want to access is an object. However, there are rare cases where that object is null, which causes the following error :
Can not read property < property > of undefined.
When the object is null, Vue redirects the user to another page, but anyway since the object is called in the template it still crashes the error in the console.
In the meantime, to solve the problem, I've been using computed properties where I check the value from the store and return an empty object if it's null.
I have also used conditions directly in the template.
Both these solutions work, but on one hand an empty object doesn't follow the language's idiom, or to put it another way it feels like it shouldn't be used that way. On the other hand, since my sometimes-null object from the store is displayed in lots of different places in the template, using a condition to check if the object is null every time it's called really ends up making the template "heavy".
Which solution do you suggest? Are there better alternatives and what are the best practices in this scenario?
Thanks.
Upvotes: 0
Views: 1282
Reputation: 222498
This can be achieved with ES2020 optional chaining operator (Elvis operator), either natively or with respective Babel transform:
store?.non?.existent?.property
Vue uses Buble instead of Babel for template syntax, this limits supported features to ones supported by Buble.
Optional chaining isn't supported. It's suggested to use script section for features that aren't supported in templates. Third-party (Lodash _.get
) or custom solutions for safe navigation can also be used in templates instead, e.g.:
Vue.mixin({
methods: {
safeGet: (o, path) => (
path.replace(/\[(\d+)\](?=[[.]|$)/g, '.$1').split('.')
.reduce((o, key) => (o == null) ? null : o[key], o)
)
}
})
...
{{safeGet(store, 'non.existent.property')}}
Upvotes: 1