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

问题描述 投票:1回答:2

给出以下组件:

<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道具包含太多字段,无法单独传递每个字段。
javascript vue.js vue-props
2个回答
1
投票

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

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

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.