'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 1:[1]
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>
Solution 2:[2]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Boussadjra Brahim |
Solution 2 | carlosabcs |