Damon
Damon

Reputation: 4484

Vue.js How can I pass an empty object as props to the same form (create/update)?

I am trying to use the same form to create and update an object.

In my page, I am passing in all colors like this:

<my-form-component :colors="colors" :foo="foo" />

My form component looks like this:

// MyFormComponent.vue

<input type="text" v-model="foo.name" />

<select id="colorId" v-model="foo.colorId">
    <option value="">Select</option>
    <option v-for="color in colors"
            :key="color.id"
            :value="color.id">
            {{ color.name }}
    </option>
</select>

...

<script>
    ...

    props: {
        colors: {
            type: Array,
            required: true,
        },
        foo: {
            type: Object,
            required: false,
            default: undefined,
        },
    }
</script>

When I am editing my object foo everything works great! I am passing in foo & colors as as props.

The problem is when creating a new object, foo doesn't exist (obviously) so I am getting an error, "TypeError: Cannot read property 'colorId' of undefined"

I understand exactly why it is angry--since I am not passing in foo, it does not have colorId.

If I create a foo data object, I get an error that since I am passing foo as props, use that instead.

How can I pass in an empty object as props so I do not get the undefined error? Thank you for any suggestions!

Upvotes: 4

Views: 5011

Answers (1)

tao
tao

Reputation: 90068

Default accepts a factory function:

props: {
  foo: {
    type: Object,
    default: () => ({})
  }
}

See Prop Validation.

Relevant bit:

...
  // Object or array defaults must be returned from  
  // a factory function  
  default: function () {  
    return { message: 'hello' }  
  }
...

Upvotes: 7

Related Questions