[英]How to pass object's attribute as prop to vue.js component
给定以下组件:
<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
道具用一些默认值填充数据字段,这些默认值也可以在使用组件时定义。
但是我怎么能只传递一个 prop blueprint
字段呢? 当我这样做时:
<my-component :blueprint="{attribute: someVar}" />
otherAttribute
,默认blueprint
的otherAttribute
将消失。
我可以只设置道具的一个字段并将其与另一个的默认值合并,如下所示:
<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 {
blueprintDefault: {
attribute: 0,
otherAttribute: 5
}
}
},
mounted () {
this.blueprint = {...this.blueprintDefault, ...this.blueprint}
}
}
</script>
我找到了一个似乎对我有用的解决方案。 我的组件现在看起来像这样:
<script>
export default {
name: 'MyComponent',
props: {
blueprint: {
type: Object
}
},
data () {
return {
attribute: this.blueprint.attribute ?? 0,
otherAttribute: this.blueprint.otherAttribute ?? 5
}
}
}
</script>
我删除了道具的default
部分,现在直接在数据中设置默认值。 这样,如果我的blueprint
道具不包含所有属性,其他默认值仍将存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.