Skip to content

Instantly share code, notes, and snippets.

@rokde
Last active March 13, 2018 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rokde/5c7b9b2ec8bacbb2c5e665cacd7b8352 to your computer and use it in GitHub Desktop.
Save rokde/5c7b9b2ec8bacbb2c5e665cacd7b8352 to your computer and use it in GitHub Desktop.
Explanation of using v-model with two-way sync for input form controls within your own custom components.

While v-model is a powerful asset for adding two-way data-binding to vanilla components, it’s not always readily apparent how to add support for v-model to your own custom components. Turns out though, it’s pretty simple.

All your component needs to do to be compatible with v-model is accept a :value property and emit an @input event when the user changes the value.

Examples below.

Source/Copyright: https://alligator.io/vuejs/add-v-model-support/

<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>
<template>
<div class="date-picker">
Month: <input type="number" ref="monthPicker" :value="splitDate.month" @input="updateDate()"/>
Year: <input type="number" ref="yearPicker" :value="splitDate.year" @input="updateDate()"/>
</div>
</template>
<script>
export default {
props: ['value'],
computed: {
splitDate() {
const splitValueString = this.value.split('/');
return {
month: splitValueString[0],
year: splitValueString[1]
}
}
},
methods: {
updateDate() {
const monthValue = this.$refs.monthPicker.value;
const yearValue = this.$refs.yearPicker.value;
this.$emit('input', `${monthValue}/${yearValue}`);
}
}
};
</script>
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment