Format localized Vuetify datepicker value with Vue mixin

Format localized Vuetify datepicker value with Vue mixin

The example for showing a formatted date in a datepicker with Vuetify uses a computed property to format the value in the text field. Something like this:

<v-menu>
  <template v-slot:activator="{ on }">
    <v-text-field
      :value="formattedDate"
      :label="$t('domain.manageFunds.form.inceptionDate')"
      readonly
      v-on="on"
    />
  </template>
  <v-date-picker v-model="form.fields.inceptionDate.value" />
</v-menu>

With a computed property (or a getter function in Typescript):

get formattedDate(): string {
  return dayjs(this.form.fields.inceptionDate.value)
    .locale(this.language)
    .format('L');
}

The issue with this is, that we need to write a getter function for every single datepicker we're using in our application. To prevent this work, we instead can create a single function and define it as a Vue mixin:

Vue.mixin({
  methods: {
    formatDatePickerValue: (date: string) => {
      if (date === '') {
        return '';
      }

      // This language can come from anywhere, here it's stored in Vuex
      const language = store.state.app.selectedLanguage!;

      return dayjs(date).locale(language).format('L');
    },
  },
});

This mixin is available in all templates so we can use it for the value:

<v-menu>
  <template v-slot:activator="{ on }">
    <v-text-field
      :value="formatDatePickerValue(form.fields.inceptionDate.value)"
      :label="$t('domain.manageFunds.form.inceptionDate')"
      readonly
      v-on="on"
    />
  </template>
  <v-date-picker v-model="form.fields.inceptionDate.value" />
</v-menu>