Passing an Object as a prop and syncing nested form values with Vuetify text fields

Viewed 503

I am trying to pass the inputted form data back to the parent.

Parent:

  <AddForm
    :value.sync="field"
  ></AddForm>

data: () => ({
  field: {
    id: "",
    name: "",
  },
})

Child AddForm:

  <v-text-field :value="value.id" @input="addId"></v-text-field>
  <v-text-field :value="value.name" @input="addName"></v-text-field>

  props: {
    value: { type: Object, required: true },
  },

    methods: {
      addId(e) {
        this.$emit("update:field.id", e);
      },
      addName(e) {
        this.$emit("update:field.name", e);
      },
    }

Not sure what I'm missing ?

2 Answers

I think you should only update field without specifying the nested fields by spreading this.value and add the updated field and emitting it as payload :

    <v-text-field :value="value.id" @input="addId"></v-text-field>
    <v-text-field :value="value.name" @input="addName"></v-text-field>

  props: {
    value: { type: Object, required: true },
  },

    methods: {
      addId(e) {
        this.$emit("update:field",{...this.value, id: e});
      },
      addName(e) {
        this.$emit("update:field", {...this.value,name:e});
      },
    }

Even though you can do like @BoussadjraBrahim said, I think if that component is a form, it should act like a form, and then you only pass the data back to parent when the user try to submit the form.

Something like this, the code below is not valid, is just to demonstrate my point

FormComponent.vue

<template>
   <v-form :valid="valid" @submit.prevent="sendData">
      <v-text-field :value="value.id" :rules="[someValidation]" @input="id" />
      <v-text-field :value="value.name" @input="name" />
      <v-btn type="submit">Save</v-btn>
   </v-form>
</template>

<script>
.....
props: {
   value: { type: Object, required: true },
},

data() {
   return {
      valid: false,
      id: '',
      name: '',
   }
},

methods: {
      sendData() {
        this.$emit("submit",{id: this.id, name: this.name });
      },
}
</script>

Then in parent you get the information when the user submits the information.

With this approach you can let the logic to validate the input to the component, which to me makes a lot of sense.

Related