JSFiddle - React, Tailwind, and code Playground
http://acdcjunior.github.io/how-bind-date-object-to-input-date-vue.js-v-model.html
by acdcjunior
HTML
<script src="//unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
<div id="app">
myDate: <input-date v-model="myDate"></input-date>
<p>myDate: {{ myDate }}</p>
<button @click="setMyDateToToday">Set date one to today</button>
<button @click="addADayToMyDate">Add a day to my date</button>
</div>
<br><br><br>
<h3>Details at: <a href="http://acdcjunior.github.io/how-bind-date-object-to-input-date-vue.js-v-model.html">http://acdcjunior.github.io/how-bind-date-object-to-input-date-vue.js-v-model.html</a></h3>
JavaScript
Vue.component('input-date', {
template: `
<input
type="date"
ref="input"
v-bind:value="dateToYYYYMMDD(value)"
v-on:input="updateValue($event.target)"
v-on:focus="selectAll"
>
`,
props: {
value: {
type: Date,
default: new Date()
}
},
methods: {
dateToYYYYMMDD(d) {
return d && new Date(d.getTime()-(d.getTimezoneOffset()*60*1000)).toISOString().split('T')[0];
},
updateValue: function (target) {
this.$emit('input', target.valueAsDate);
},
selectAll: function (event) {
// Workaround for Safari bug
// http://stackoverflow.com/questions/1269722/selecting-text-on-focus-using-jquery-not-working-in-safari-and-chrome
setTimeout(function () {
event.target.select()
}, 0)
}
}
});
new Vue({
el: '#app',
data: {
myDate: new Date('2011-04-11T00:00:01Z') // DO notice this date is set in UTC (Greenwich time) not your current timezone
},
methods: {
setMyDateToToday() {
this.myDate = new Date();
},
addADayToMyDate() {
// use the if because myDate can be null
if (this.myDate) {
// notice we don't just call .setDate(...) in myDate, instead
// we create a new Date object and set it to this.myDate, so vue can detect it changed
// this is not a caveat of this specific solution, but of any binding of dates
this.myDate = new Date(this.myDate.setDate(this.myDate.getDate() + 1));
}
}
}
});
// Notes:
// We use `myDate && new Date(myDate.getTime()-(myDate.getT...` instead
// of just `new Date(myDate.getTime()-(myDate.getT...` because `myDate` can be null.