Learn how to use Vuetify to build a custom date picker component. Follow our snippet code tutorial and you'll be able to create a powerful, user-friendly date picker in no time!
Build the selectable date picker component
In Vuetify the v-date-picker is only the flat picker of the date so in order to have a selectable date picker field we need to combine the usage of the v-text-field to show the selected date, the v-date-picker to show the flat date picker and lastly the v-menu to manage the popup/close of the v-date-picker when the user selects the field or pick a date.
In ./src/components/BaseDatePicker.vue
<template>
<v-menu v-model="showDatePicker" min-width="auto">
<template v-slot:activator="{ on, attrs }">
<v-text-field
:label="label"
:value="content"
:rules="rules"
:placeholder="placeholder"
@click:clear="content = null"
v-on="on"
v-bind="attrs"
prepend-inner-icon="mdi-calendar-blank-outline"
clearable
>
</v-text-field>
</template>
<v-date-picker
v-model="content"
@change="showDatePicker = false"
></v-date-picker>
</v-menu>
</template>
<script>
export default {
props: {
value: {
required: true,
},
label: {
type: String,
required: true,
},
placeholder: {
type: String,
default: 'YYYY-MM-DD',
},
rules: {
type: Array,
default: () => [],
},
required: {
type: Boolean,
default: false,
},
},
data() {
return {
showDatePicker: false,
};
},
computed: {
content: {
get() {
return this.value;
},
set(val) {
this.$emit('input', val);
},
},
},
};
</script>
Sample usage
In any component, the page that you want to use the component.
<template>
<v-container>
<v-row class="text-center">
<v-col cols="4">
<base-date-picker label="Datepicker" v-model="date"></base-date-picker>
</v-col>
</v-row>
</v-container>
</template>
<script>
import BaseDatePicker from '@/components/BaseDatePicker.vue';
export default {
components: {
BaseDatePicker,
},
data() {
return {
date: null,
};
},
};
</script>