【问题标题】:How to pass object's attribute as prop to vue.js component如何将对象的属性作为道具传递给 vue.js 组件
【发布时间】:2020-02-27 11:21:22
【问题描述】:

给定以下组件:

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

但是我怎样才能只传递propblueprint的一个字段呢? 当我这样做时:

<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 属性有太多字段,无法单独传递每个字段。

【问题讨论】:

  • MyComponent 是你自己构建的还是来自其他库?
  • 它是我建的。我想我现在找到了解决方案,谢谢!

标签: javascript vue.js vue-props


【解决方案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>

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-11
      • 2016-12-18
      • 2018-12-05
      • 2018-08-01
      • 2023-04-08
      • 2019-01-22
      • 2021-03-30
      • 2021-07-12
      相关资源
      最近更新 更多