Vue.js 3 — Bind a V-Model Value to an HTML Date Input

Vue.js uses the v-model directive on components to create a two-way binding. At first, Vue assigns the value of the model attribute to the component or native HTML element. And second, Vue updates the model value anytime it’s changed, for example, due to a changed text in an HTML input field.

This tutorial shows you how to use v-model on an HTM date input field to bind an existing value.

Vue.js 3 Series Overview

Bind a V-Model Value to an HTML Date Input

In Vue.js you can bind an existing date value to an HTML input element. You must provide the existing date value as a string in the format of YYYY-MM-DD. The HTML date input element will then pick up your existing value when provided via v-model:

<script>  
const date = '2023-07-20'

 // the date value bound to `v-model` must have the format 'YYYY-MM-DD'
const value = ref(date)  
</script>

<template>  
    <input type="date" v-model="value" />
</template>  

Vue’s two-way binding also works and updates your date attribute (in the format of YYYY-MM-DD) when changing the value inside of the HTML date input field.

How to Format a Date in YYYY-MM-DD

We have a tutorial here on Future Studio showing you how to format a date instance in YYYY-MM-DD. You may visit and follow the tutorial if you want to format a date in the mentioned format.

Why Formatting the Date in YYYY-MM-DD?

The v-model directive is a shortcut for a more verbose functionality. The Vue.js compiler expands v-model to the following:

<input v-model="searchText" />

<!-- is equivalent to -->

<input  
  :value="searchText"
  @input="searchText = $event.target.value"
/>

You can assign a default value to <input type="date" /> inputs by using a date strings format. This format uses the YYYY-MM-DD format for date inputs and is the reason why the value of your v-model instance must use it.

Enjoy using date variables with Vue and HTML date inputs!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.