Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way binding in a custom input field in vue

I am having problems getting access to the text am entering into a custom input field using the v-model vue directive, here are the codes for both the custom input component and the App.vue

This is my custom input field

Input.vue

<template>
    <label >{{label}}</label>
    <input v-model="bindTo" type='type'  required>
</template>

<script>
export default {
    props:['label','type','bindTo']
}
</script>

App.vue

<template>

    <!-- Email -->
        <Input type="email" label="Email" :bindTo="email"/>
        <p>Email : {{email}}</p>


</template>

<script>
import Input from "./Input.vue";

export default {
    components:{
        Input,
    },
data() {
    return {
        email:"",
        password:"",
        role:"developer",
        terms:false,
        tempSkill:"",
        skills:[],
        passwordError:"",
        emailError:"",
    }
},


</script>

I can't have access to the value in the email in my data method. What might be wrong?

like image 453
Daniel Sogbey Avatar asked Oct 30 '25 21:10

Daniel Sogbey


1 Answers

Going through the docs thoroughly I found the solution that helped solve my problem

Input.vue

<template>
    <label >{{label}}</label>
    <input :value="modelValue" type='type' @input="$emit('update:modelValue',$event.target.value)"  required>
</template>

<script>
export default {
    props:['label','type','modelValue'],
    emits:['update:modelValue']
}
</script>

Then in App.vue

<template>

    <!-- Email -->
        <Input type="email" label="Email" v-model="email"/>
        <p>Email : {{email}}</p>


</template>

<script>
import Input from "./Input.vue";

export default {
    components:{
        Input,
    },
data() {
    return {
        email:"",
        password:"",
        role:"developer",
        terms:false,
        tempSkill:"",
        skills:[],
        passwordError:"",
        emailError:"",
    }
},


</script>

For more details visit the docs as there are other ways to make it work aside this approach https://vuejs.org/guide/components/events.html

like image 138
Daniel Sogbey Avatar answered Nov 01 '25 11:11

Daniel Sogbey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!