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;
});
}
}
});
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue.
Interpolation is the insertion of something of a different nature into something else. In the Vue. js context, this is where you would use mustache syntax (double curly braces) to define an area where you can inject data into a component's HTML template.
You 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With