Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a default value for undefined object property in VueJS interpolation?

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;
           });
       }
   }
});
like image 675
jonan.pineda Avatar asked Nov 19 '16 02:11

jonan.pineda


People also ask

How do you pass a prop number in Vue?

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.

What is $t in Vuejs?

Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue.

What is the text interpolation data binding syntax in VUE JS?

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.


2 Answers

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.

like image 125
str Avatar answered Sep 17 '22 23:09

str


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.

like image 37
GuyC Avatar answered Sep 19 '22 23:09

GuyC