I have a set of ‘text-input’ custom components which house some boilerplate markup and an ‘input’ element.
One way of getting the value of the ‘text-input’ in to it’s parent is to $emit an event when the value has changed.
I need to capture and handle the $emit with a v-on for every text-input component:
JavaScript
x
4
1
<text-input v-on:valueUpdated="storeInputValue" name='name'></text-input>
2
<text-input v-on:valueUpdated="storeInputValue" name='email'></text-input>
3
<text-input v-on:valueUpdated="storeInputValue" name='phone'></text-input>
4
I feel that this introduces too much repetition in the code, and I was wondering if there were a way to have the v-on listener on the component template itself:
JavaScript
1
4
1
<template v-on:valueUpdated="storeInputValue">
2
3
</template>
4
So that there is a ‘default’ v-on listener for this component, every time it is used.
Advertisement
Answer
You can use v-model
on custom components.
html
JavaScript
1
7
1
<div id="app>
2
<text-input v-model="user.name" name="'name'"></text-input>
3
<text-input v-model="user.email" name="'email'"></text-input>
4
<text-input v-model="user.phone" name="'phone'"></text-input>
5
<h4>{{user}}</h4>
6
</div>
7
script
JavaScript
1
28
28
1
Vue.component('text-input', {
2
name: 'text-input',
3
template: `
4
<div>
5
<label>{{name}}</label>
6
<input type="text" :value="value" @input="storeInputValue($event.target.value)" />
7
</div>
8
`,
9
props: ['value', 'name'],
10
methods: {
11
storeInputValue(value){
12
this.$emit('input', value);
13
}
14
}
15
});
16
17
//parent component
18
new Vue({
19
el: '#app',
20
data: {
21
user: {
22
name: '',
23
email: '',
24
phone: ''
25
}
26
}
27
});
28
here is the example fiddle