1

Given the following 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>

I want to use the blueprint prop to populate data fields with some default values which could also be defined when using the component.

But how can I pass only one field of prop blueprint? When I do this:

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

the otherAttribute of the default blueprint will be gone, of course.

Can I only set the one field of the prop and merge it with the default of the other, something like this:

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

Sadly the blueprint prop has too many fields to pass each field on it's own.

2
  • MyComponent is built by you or it comes from other libraries? Commented Feb 27, 2020 at 11:25
  • It is built by me. And I think I found a solution now, thanks! Commented Feb 27, 2020 at 11:43

2 Answers 2

1

yeah, your Answer is fine. Here is my solution

<script>
export default {
  name: 'MyComponent',
  props: {
    blueprint: {
      type: Object
    }
  },
  data () {
    return {
      blueprintDefault: {
          attribute: 0,
          otherAttribute: 5 
      }
    }
  },
  mounted () {
   this.blueprint = {...this.blueprintDefault, ...this.blueprint}
  }
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

I found a solution that seems to work for me. My component now looks like this:

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

I removed the default part of the prop and now set the default values directly in the data instead. That way if my blueprint prop does not include all attributes, the other default values will still be there.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.