Home > Software design >  how to use an Emit with a v-model?
how to use an Emit with a v-model?

Time:11-21

i am on Vue3, and i try to catch a value from the child to the parent. So my code is :

On the parent :

<template>
  <input-form v-model="valueSuperficie" label="Surface en m²" />
</template>

<script>
   data() {
     return {
      valueSuperficie = null,
      }
   }
</script>

and on the child i try to make an emit.

<template>
<input 
      v-on:change="$emit('userEntry', $event.target.valueInput)"
      v-model="userEntry"
/>
</template>

<script>
  data() {
    return {
      userEntry: this.valueInput,
    };
  },
  emits: ["userEntry"],

</script>

I know that my code is incorrect, what I would like is to succeed in storing the value of the child, namely userEntry in the data valueSuperficie of the parent. Thanks

CodePudding user response:

In child component define a prop called modelValue and emit an event named update:modelValue :

<template>
   <input 
      v-on:input="$emit('update:modelValue', $event.target.value)"
      :value="modelValue"
/>
</template>

<script>
export default{
  props:{
     modelValue:String
    },
  emits: ["update:modelValue"],
}
</script>

CodePudding user response:

I suppose the child component name is input-form. The parent should process the event the child is triggering using a callback function. That function would be a method that assigns the received value to the inner value called valueSuperficie.

So the parent should look like this:

<template>
  <input-form @user-entry="onUserEntry" label="Surface en m²" />
</template>

<script>
   data() {
     return {
      valueSuperficie = null,
      }
   },
   methods: {
     onUserEntry(valueInput) {
       this.valueSuperficie = valueInput;
     }
   }
</script>
  • Related