1

给定以下组件:

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

我想使用blueprintprop 来使用一些默认值填充数据字段,这些默认值也可以在使用组件时定义。

但是我怎样才能只通过一个 prop 字段blueprint呢?当我这样做时:

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

当然,otherAttribute默认的blueprint将消失。

我可以只设置 prop 的一个字段并将其与另一个字段的默认值合并,如下所示:

<my-component :blueprint.attribute="someVar" />
<!-- It doesn't work like this, but maybe you get the idea what I want -->

可悲的是,道blueprint具有太多字段无法单独传递每个字段。

4

2 回答 2

1

是的,你的答案很好。这是我的解决方案

<script>
export default {
  name: 'MyComponent',
  props: {
    blueprint: {
      type: Object
    }
  },
  data () {
    return {
      blueprintDefault: {
          attribute: 0,
          otherAttribute: 5 
      }
    }
  },
  mounted () {
   this.blueprint = {...this.blueprintDefault, ...this.blueprint}
  }
}
</script>
于 2020-02-27T11:53:22.200 回答
0

我找到了一个似乎对我有用的解决方案。我的组件现在看起来像这样:

<script>
export default {
  name: 'MyComponent',
  props: {
    blueprint: {
      type: Object
    }
  },
  data () {
    return {
      attribute: this.blueprint.attribute ?? 0,
      otherAttribute: this.blueprint.otherAttribute ?? 5
    }
  }
}
</script>

我删除了default道具的一部分,现在直接在数据中设置默认值。这样,如果我的blueprint道具不包括所有属性,其他默认值仍然存在。

于 2020-02-27T11:41:56.370 回答