Home > Enterprise >  Vue 3 V-Model Passing to Grandchild Component
Vue 3 V-Model Passing to Grandchild Component

Time:10-17

I have three components that I would like to pass a reactive model down through from the parent -> child -> grandchild (vee-validate Field).

So parent component would look like:

<template>
  <child v-model="formData" />
</template>
.
.
.
setup() {
  const formData = ref<CreateAccount>({
      email: "",
      firstName: "",
      lastName: ""
  });

  return {
    formData,
  };
}

Child component (with grandchild component) looks like:

<template>
  <Field
    type="text"
    name="email"
    v-model="modelValue.email" ????
  />
</template>

export default defineComponent({
    name: "step-2",
    components: {
      Field,
    },
    props: {
      modelValue: {
        type: Object,
        required: true,
      },
    },
    emits: ["update:modelValue"],
  },
});

Now my issue is that I cannot just pass modelValue to the Field v-model prop, so I'm not sure if there is a chain of events or restructuring the child modelValue that needs to be done?

CodePudding user response:

I ended up using the following solution in my child component:

<template>
  <Field
    type="text"
    name="email"
    v-model="model.email"
  />
</template>

export default defineComponent({
  name: "step-2",
  components: {
    Field,
  },
  props: {
    modelValue: {
      type: Object,
      required: true,
    },
  },
  computed: {
    model: {
      get() {
        return this.modelValue;
      },
      set(value) {
        this.$emit("update:modelValue", value);
      },
    },
  },
},
});

CodePudding user response:

When a child is a passthrough component, desugared syntax can be used instead of v-model to pass data in both directions:

  <child v-model="formData.email" />

and

  <Field
    type="text"
    name="email"
    :modelValue="modelValue"
    @update:modelValue="$emit("update:modelValue", $event)"
  />
  • Related