如何在VueJS插值中为未定义的对象属性使用默认值?(How to use a default value for undefined object property in VueJS interpolation?)

如何在VueJS插值中为未定义的对象属性使用默认值? 我的data是一个计算变量,并且在选择框中选择selectedDataId之前是未定义的,因此vue发送“无法读取未定义”错误的属性'grandChild'

PS:我正在使用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; }); } } });

最满意答案

您可以使用以下模式:

{{ selectedData.child && selectedData.child.grandChild || 'default value' }}

它将安全地检查grandChild ,如果它是虚假的,则打印“默认值”。

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.

如何在VueJS插值中为未定义的对象属性使用默认值?(How to use a default value for undefined object property in VueJS interpolation?)

如何在VueJS插值中为未定义的对象属性使用默认值? 我的data是一个计算变量,并且在选择框中选择selectedDataId之前是未定义的,因此vue发送“无法读取未定义”错误的属性'grandChild'

PS:我正在使用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; }); } } });

最满意答案

您可以使用以下模式:

{{ selectedData.child && selectedData.child.grandChild || 'default value' }}

它将安全地检查grandChild ,如果它是虚假的,则打印“默认值”。

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.