vue.jsvuejs3emitv-model

how to use an Emit with a v-model?


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


Solution

  • 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>