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">
<p>
Formatting the date in the template:
<input type="date" :value="myDate && new Date(myDate.getTime()-(myDate.getTimezoneOffset()*60*1000)).toISOString().split('T')[0]"
@input="myDate = $event.target.valueAsDate">
</p>
<p>
Formatting the date using a helper method:
<input type="date" :value="dateToYYYYMMDD(myDate)"
@input="myDate = $event.target.valueAsDate">
</p>
<p>
<code>
myDate: {{ myDate }}</code>
</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
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
myDate: new Date('2011-04-11T00:01:01Z') // note 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));
}
},
dateToYYYYMMDD(d) {
return d && new Date(d.getTime()-(d.getTimezoneOffset()*60*1000)).toISOString().split('T')[0]
}
}
});
// Notes:
// We use `myDate && myDate.toISOString().split('T')[0]` instead
// of just `myDate.toISOString().split('T')[0]` because `myDate` can be null.