如何将对象的属性作为 prop 传递给 vue.js 组件

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 道具用一些默认值填充数据字段,这些默认值也可以在使用组件时定义。

但是我怎样才能只传递一个属性blueprint呢? 当我这样做时:

<my-component :blueprint="{attribute: someVar}" />

默认 blueprintotherAttribute 当然会消失。

我可以只设置prop的一个字段,然后将其与另一个字段的默认值合并吗,像这样:

<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>

我删除了道具的 default 部分,现在直接在数据中设置默认值。这样,如果我的 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>