如何设置对象prop
的嵌套属性的默认值?
显然,仅当第一级对象prop
为undefined
时,Vue才会解析嵌套属性的默认值。
示例:
Vue.component('example', {
props: {
options: {
type: Object,
default: function() {
return {
nested: {
type: Object,
default: function(){
return 'default value'
}
}
}
}
}
})
答案 0 :(得分:2)
显然,Vue只解析嵌套属性的默认值 第一级对象道具未定义。
是的,这是有道理的,因为如果你没有外部对象,你将无法拥有内部或嵌套属性。
所以我认为它更具可读性,只需将默认{}
设置为第一级对象的emtpy对象,您应该针对 undefined 或 null <进行自己的防御性验证/ strong>,如同下面的例子:
<script>
export default {
props: {
option: {
type: Object,
default: () => {},
required: false
}
},
computed: {
optionReceived: function () {
const defaultNestedValue = 'Some default value'
const option = this.option.nested || defaultNestedValue;
return option;
}
}
}
</script>
答案 1 :(得分:2)
我认为最好让您的数据结构易于使用且尽可能平坦。因为Vue中的嵌套道具绝不是一个好的选择。
假设您在Vue组件中提到的options
内部有很多属性。
示例:
props: {
options: {
bookAttributes: {
colorAttributes: { coverColor: 'red', ribbonColor: 'green' },
sizeAttributes: { coverSize: 10, ribbonSize: 2 },
...
}
}
}
你可以让它们像这样平坦,以便更好地理解。
props: {
coverSize: 10,
coverColor: 'red',
ribbonColor: 'green,
ribbonSize: 2 ...
}
然后你和你的同事可以愉快地使用你的组件:
<your-component>
coverSize="15"
coverColor="blue"
ribbonColor="red"
ribbonSize="3"
</your-component>
祝你好运,祝你好运。