Custom events can also be used to create custom inputs that work with v-model
. Remember that:
<input v-model="searchText">
does the same thing as:
<input
v-bind:value="searchText"
v-on:input="searchText = $event.target.value"
>
When used on a component, v-model
instead does this:
<custom-input
v-bind:value="searchText"
v-on:input="searchText = $event"
></custom-input>
Example:
Say you have a date picker component that accepts a month and a year value in an object with the form: {month: 1, year: 2017}. You want that component to have two inputs, one for the month and one for the year, and update the bound object through v-model. Here’s how you would implement that.
DatePicker.vue
<template>
<div class="date-picker">
Month: <input type="number" ref="monthPicker" :value="value.month" @input="updateDate()"/>
Year: <input type="number" ref="yearPicker" :value="value.year" @input="updateDate()"/>
</div>
</template>
<script>
export default {
props: ['value'],
methods: {
updateDate() {
this.$emit('input', {
month: +this.$refs.monthPicker.value,
year: +this.$refs.yearPicker.value
})
}
}
};
</script>
And here’s how another component would use the date picker:
WrapperComponent.vue
<template>
<div class="wrapper">
<date-picker v-model="date"></date-picker>
<p>
Month: {{date.month}}
Year: {{date.year}}
</p>
</div>
</template>
<script>
import DatePicker from './DatePicker.vue';
export default {
components: {
DatePicker
},
data() {
return {
date: {
month: 1,
year: 2017
}
}
}
})
</script>
As you can see, it simply takes a :value property and emits an @input event with the updated date. Nothing too complicated at all!