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?
CodePudding user response:
In Vue.js, you just simply add v-bind="$attrs"
and v-on="$listeners"
, so you can forward everything from parent to child component.
Input.vue
<template>
<label >{{label}}</label>
<input v-bind="$attrs" v-on="$listeners">
</template>
<script>
export default {
props: ['label']
}
</script>
App.vue
<template>
<!-- Email -->
<Input type="email" label="Email" v-model="email" required/>
<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>
CodePudding user response:
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