A
A
Alexey2020-11-10 17:01:53
Vue.js
Alexey, 2020-11-10 17:01:53

Is it possible to use $t (Vue I18n) in a Vue plugin?

Vue CLI, application on single-file components.
Vue 2.x, Vue i18n

I'm creating a plugin that will be a global library of functions that can be reached from any component. For example, you need to request a date from different components, in which the month is in text format, and the month needs to be translated into the current language. The question is: is it possible to somehow access the $t translator directly in the plugin?
For example, this doesn't work:

export default {
  install (Vue) {
    const fn = {
      getBirthLabel (year, month, day) {
        let label = ''
        if (day) label += `${day} `
        if (month) label += `${this.$t('month')} `
        if (year) label += year
        return label
      }
    }
    Vue.prototype.$f = fn
  }
}

Tried to pass $t to a function:
getBirthLabel (year, month, day, t) {
        let label = ''
        if (day) label += `${day} `
        if (month) label += `${t('month')} `
        if (year) label += year
        return label
      }

- Did not work out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aleks_Ko, 2020-11-10
@Aleks_Ko

And what if in this case the first role is assigned to
Intl.DateTimeFormat
https://developer.mozilla.org/en/docs/Web/JavaScri...
Something like this
- make a filter for the date;
- place Intl.DateTimeFormat in the filter and change the desired locale there already using vue 18
With the change of locale, the date format + the name of the month should also be in another language

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question