给出以下组件:
<script>
export default {
name: 'MyComponent',
props: {
blueprint: {
type: Object,
default () {
return {
attribute: 0,
otherAttribute: 5
}
}
}
},
data () {
return {
attribute: this.blueprint.attribute,
otherAttribute: this.blueprint.otherAttribute
}
}
}
</script>
我想使用blueprint
属性用一些默认值填充数据字段,这些默认值在使用组件时也可以定义。
但是我怎么只能传递道具blueprint
的一个字段?当我这样做时:
<my-component :blueprint="{attribute: someVar}" />
otherAttribute的blueprint
当然会消失。 我只能设置道具的一个字段并将其与另一个字段的默认值合并,如下所示:
<my-component :blueprint.attribute="someVar" />
<!-- It doesn't work like this, but maybe you get the idea what I want -->
可悲的是blueprint
道具包含太多字段,无法单独传递每个字段。
我找到了一个似乎对我有用的解决方案。我的组件现在看起来像这样:
<script>
export default {
name: 'MyComponent',
props: {
blueprint: {
type: Object
}
},
data () {
return {
attribute: this.blueprint.attribute ?? 0,
otherAttribute: this.blueprint.otherAttribute ?? 5
}
}
}
</script>