How to use a default value for undefined object property in VueJS interpolation? My data
is a computed variable and is undefined at first before selecting a selectedDataId
in a selectbox so vue sends a "cannot read property 'grandChild' of undefined" error.
P.S.: I'm using lodash
<div>
{{ selectedData.child.grandChild }}
</div>
new Vue({
data: {
selectedDataId: null,
selectedData: {},
data: [ //array of objects here ]
},
computed: {
selectedData() {
return _.find(this.data, (d) => {
return d.id == this.selectedDataId;
});
}
}
});
How to use a default value for undefined object property in VueJS interpolation? My data
is a computed variable and is undefined at first before selecting a selectedDataId
in a selectbox so vue sends a "cannot read property 'grandChild' of undefined" error.
P.S.: I'm using lodash
<div>
{{ selectedData.child.grandChild }}
</div>
new Vue({
data: {
selectedDataId: null,
selectedData: {},
data: [ //array of objects here ]
},
computed: {
selectedData() {
return _.find(this.data, (d) => {
return d.id == this.selectedDataId;
});
}
}
});
Share
Improve this question
asked Nov 19, 2016 at 2:51
jonan.pinedajonan.pineda
1,30411 silver badges19 bronze badges
1
|
3 Answers
Reset to default 16You could use the following pattern:
{{ selectedData.child && selectedData.child.grandChild || 'default value' }}
It will safely check for grandChild
and print "default value" if it is falsy.
you are declaring selectedData twice, you should remove it from the data object.
as for an issue with it being undefined you could just test for this within your templates: v-if="selectedItem"
or methods: if (selectedItem)
You don't really need lodash here as Vue has a built in filter method:
selectedData() {
const selectedItem = this.data.filter((item) => {
return item.id == this.selectedDataId
})
return selectedItem.length ? selectedItem[0] : {} // i'd set null here on fail
}
Rather than a default object I would probably just set the above to null
if the selectedItem.length
is 0. Then the above tests will work, passing an empty object will make them truthy.
try this
selectedData() {
return _.chain(this.data)
.find({id: this.selectedDataId})
.defaults(...default object...)
.value()
}
{{ selectedData.child && selectedData.child.grandChild }}
– Nico Commented Nov 19, 2016 at 2:55