How do I select only year from Vuetify Datepicker ?
I have a requirement where I need a drop down to select only the year YYYY
.
But the default Vuetify date-picker picks the whole YYYY-MM-DD
format.
I see in source code of date picker that year
type is planned and will be implemented in future. From source code props:
type: String, default: 'date', validator: type => ['date', 'month'].includes(type) // TODO: year },
But I can achieve this with workaround no-title
, preventing date picker to switch to month/day window and closing v-menu
. You can see working example - Changed codepen from docs.
You can play also with formatting title and header to get better result if you want.
It isn't supported using the type
prop.
But a workaround is setting this.$refs.picker.activePicker
to type YEAR
. We can create a watcher to watch the menu property, and change activePicker
to YEAR
when the menu is opened:
watch: {
menu (val) {
val && this.$nextTick(() => (this.$refs.picker.activePicker = 'YEAR'))
}
}
Next, we need to close the menu as soon as the user selects a year. We do it by adding @click:year
event on the picker:
<v-date-picker
v-model="year"
ref="picker"
no-title
scrollable
@click:year="saveYear(year)"
>
<v-spacer></v-spacer>
<v-btn text color="primary" @click="menu = false">Cancel</v-btn>
<v-btn text color="primary" @click="saveYear(year)">OK</v-btn>
</v-date-picker>
The saveYear
method:
saveYear(year) {
this.$refs.menu.save(year)
// Reset activePicker to type YEAR
this.$refs.picker.activePicker = 'YEAR'
// Close the menu/datepicker
this.menu = false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With