最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use a default value for undefined object property in VueJS interpolation? - Stack Overflow

programmeradmin1浏览0评论

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
  • I'm not familiar with Vue.js, but in plain JS you could check that the properties are defined with: {{ selectedData.child && selectedData.child.grandChild }} – Nico Commented Nov 19, 2016 at 2:55
Add a comment  | 

3 Answers 3

Reset to default 16

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.

try this

selectedData() {
    return _.chain(this.data)
        .find({id: this.selectedDataId})
        .defaults(...default object...)
        .value()
}
发布评论

评论列表(0)

  1. 暂无评论