Vue Datepicker Example Tutorial From Scratch. For this tutorial, we will use the library called vuejs-datepicker. It is a simple Vue.js datepicker component. There are some supports about datepicker including disabling of dates, inline mode, translations.
Vue Datepicker Example Tutorial
First, install the Vue.js using Vue CLI. So let us do that.
#1: Install Vue.js and other libraries
vue create dates
Go inside the folder.
cd dates
Install the vuejs-datepicker using the following command.
npm install vuejs-datepicker --save # or yarn add vuejs-datepicker
Also, install the Bootstrap 4 using the following command.
yarn add bootstrap
Okay, now replace the following code inside src >> App.vue file.
<template> <div id="app" class="container"> <h3>Vue.js Datepicker</h3> <form> <div class="form-group"> <vuejs-datepicker></vuejs-datepicker> </div> <div class="form-group"> <button class="btn btn-success">Submit</button> </div> </form> </div> </template> <script> import vuejsDatepicker from 'vuejs-datepicker'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; export default { name: 'app', components: { vuejsDatepicker } } </script>
Go to the terminal and start the dev server.
npm run serve
Go to the http://localhost:8080/
#2: Props in Vue.js Datepicker
There are many properties available to work with Datepicker.
<vuejs-datepicker format="dd/MM/yyyy" placeholder="Add Date" clear-button-icon="true" ></vuejs-datepicker>
Also, other options are the following.
Prop | Type | Default | Description |
---|---|---|---|
value | Date|String | Date value of the datepicker | |
name | String | Input name property | |
id | String | Input id | |
format | String|Function | dd MMM yyyy | Date formatting string or function |
full-month-name | Boolean | false | To show the full month name |
language | Object | en | Translation for days and months |
disabled-dates | Object | See below for configuration | |
placeholder | String | Input placeholder text | |
inline | Boolean | To show the datepicker always open | |
calendar-class | String|Object | CSS class applied to the calendar el | |
input-class | String|Object | CSS class applied to the input el | |
wrapper-class | String|Object | CSS class applied to the outer div | |
monday-first | Boolean | false | To start the week on Monday |
clear-button | Boolean | false | Show an icon for clearing the date |
clear-button-icon | String | Use icon for a button (ex: fa fa-times) | |
calendar-button | Boolean | false | Show an icon that that can be clicked |
calendar-button-icon | String | Use icon for button (ex: fa fa-calendar) | |
calendar-button-icon-content | String | Use for material-icons (ex: event) | |
day-cell-content | Function | Use to render custom content in day cell | |
bootstrap-styling | Boolean | false | Output bootstrap v4 styling classes. |
initial-view | String | minimumView | If set, open on that view |
disabled | Boolean | false | If true, disable Datepicker on screen |
required | Boolean | false | Sets html required attribute on input |
typeable | Boolean | false | If true, allow the user to type the date |
use-utc | Boolean | false | use UTC for time calculations |
open-date | Date|String | If set, open on that date | |
minimum-view | String | ‘day’ | If set, lower-level views won’t show |
maximum-view | String | ‘year’ | If set, higher-level views won’t show |
#Date formatting
You can format the either using moment or using the following options.
Token | Desc | Example |
---|---|---|
d | day | 1 |
dd | 0 prefixed day | 01 |
D | abbr day | Mon |
su | date suffix | st, nd, rd |
M | month number (1 based) | 1 (for Jan) |
MM | 0 prefixed month | 01 |
MMM | abbreviated month name | Jan |
MMMM | month name | January |
yy | two digit year | 16 |
yyyy | four-digit year | 2016 |
#Function formatter
Delegates date formatting to provided function. The function will be called with date, and it has to return formatted date as a string. This allows us to use moment, date-fns, globalize or any other library to format date.
<script> methods: { customFormatter(date) { return moment(date).format('MMMM Do YYYY, h:mm:ss a'); } } </script> <vuejs-datepicker :format="customFormatter"></vuejs-datepicker>
#Translations
- Add your language as a module in the
src/locale/translations
dir. - Import and export it in the
src/locale/index
file - Add the Language to the available languages in the readme file.
- Run
npm run lint
to make sure your code formatting is in line with the required code style.
#How to apply language
Below script tag in the component.
import {en, es} from 'vuejs-datepicker/dist/locale'
In component data.
data () { return { en: en, es: es } }
html.
<vuejs-datepicker :language="es"></vuejs-datepicker>
#3: Add axios and send a POST request
Install Axios and vue-axios using the following command.
npm install axios vue-axios --save # or yarn add axios vue-axios
Import the modules inside src >> main.js file.
// main.js import Vue from 'vue' import App from './App.vue' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios) Vue.config.productionTip = false new Vue({ render: h => h(App) }).$mount('#app')
Now, define the axios post request inside the src >> App.vue file.
<template> <div id="app" class="container"> <h3>Vue.js Datepicker</h3> <form @submit.prevent="addDate"> <div class="form-group"> <vuejs-datepicker format="dd/MM/yyyy" placeholder="Add Date" clear-button-icon="true" v-model="obj.date" ></vuejs-datepicker> </div> <div class="form-group"> <button class="btn btn-success">Submit</button> </div> </form> </div> </template> <script> import vuejsDatepicker from 'vuejs-datepicker'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; export default { name: 'app', components: { vuejsDatepicker }, data(){ return { obj:{} } }, methods: { addDate() { let date = { mainDate: this.obj.date } this.axios.post('http://localhost:4000/dates/add', date).then((res) => { console.log(res.data); }); } } } </script>
Although, we have not created any backend yet. So let us do it that.
#4: Create a Node.js backend.
For this Vue Datepicker Example Tutorial demo, we will use Node.js as a backend and MongoDB as a database. So inside the root folder of reactdates, create one more folder called backend.
Go inside the folder and open the terminal and initialize the package.json file using the following command.
npm init -y
Now, install the following dependencies.
yarn add express body-parser mongoose cors # or npm install express body-parser mongoose --save
Also, install the nodemon as a development dependency.
npm install nodemon --save-dev
Now, create one file called the server.js and add the following code.
// server.js const app = require('express')(), bodyParser = require('body-parser'), cors = require('cors'), mongoose = require('mongoose'); const PORT = process.env.PORT || 4000; app.listen(PORT, () => { console.log('Listening on port ' + PORT); });
The next thing is to connect MongoDB database with our node.js application.
If you have not installed the MongoDB database then install it and then start the mongodb server.
Type the following command to start the MongoDB server.
mongod
So, Now, we need to connect our node.js application to the mongodb database.
Create one file called DB.js inside backend folder.
// DB.js module.exports = { DB: 'mongodb://localhost:27017/vuedates' };
Import this DB.js file inside our server.js file and use mongoose library to set up the database connection with MongoDB. We can also use Mongoose to save the data in the database using Mongoose ORM.
Write the following code inside the server.js file to connect our MongoDB application to the Node.js server.
// server.js const app = require('express')(), bodyParser = require('body-parser'), cors = require('cors'), mongoose = require('mongoose') config = require('./DB'); mongoose.Promise = global.Promise; mongoose.connect(config.DB, { useNewUrlParser: true }).then( () => {console.log('Database is connected') }, err => { console.log('Can not connect to the database'+ err)} ); const PORT = process.env.PORT || 4000; app.use(bodyParser.json()); app.use(cors()); app.listen(PORT, () => { console.log('Listening on port ' + PORT); });
Save a file and go to a terminal and start the node.js server using the following command. Make sure you are inside backend folder root and not in reactdates folder root.
nodemon server
#5: Create a model and Express routes
Now, we need to create two folders inside the backend folder called routes and models.
In the models’ folder, create one model called DateModel.js.
// DateModel.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; let DateModel = new Schema({ mainDate: { type: Date }, },{ collection: 'dates' }); module.exports = mongoose.model('DateModel', DateModel);
Here, we will store only one field called mainDate, and its datatype is Date.
In the routes folder, create one file called date.route.js. Add the following code inside the date.route.js file.
// date.route.js const dateRoute = require('express').Router(), DateModel = require('../models/DateModel'); dateRoute.route('/add').post(function (req, res) { let datemodel = new DateModel(req.body); datemodel.save() .then(dateSaved => { res.status(200).json({'dateSaved': 'Date is added successfully'}); }) .catch(err => { res.status(400).send("unable to save to database"); }); }); module.exports = dateRoute;
Finally, import the date.route.js file inside the server.js.
// server.js const app = require('express')(), bodyParser = require('body-parser'), cors = require('cors'), mongoose = require('mongoose'), config = require('./DB'), dateRoute = require('./routes/date.route'); mongoose.Promise = global.Promise; mongoose.connect(config.DB, { useNewUrlParser: true }).then( () => {console.log('Database is connected') }, err => { console.log('Can not connect to the database'+ err)} ); const PORT = process.env.PORT || 4000; app.use(bodyParser.json()); app.use(cors()); app.use('/dates', dateRoute); app.listen(PORT, () => { console.log('Listening on port ' + PORT); });
Now, our backend work is done. When the POST request hits the route: /dates/add, it will save the values inside the mongodb database.
Make sure, all of your three servers are running.
- Mongo database server
- Vue.js development server
- Node.js server
Save the file and go to the browser and submit the date and you will see in the console that the date is added successfully. You can check your MongoDB database.
Finally, Vue Datepicker Example Tutorial is over. Thanks for taking.

Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of cloud technologies including Google Cloud, Firebase, AWS, and Azure, and various softwares and tools.