Using vue-i18n to translate the default value for a Vue component prop

Viewed 4317

I'm using vue-i18n to handle localization in my app. I need to apply localization to the default value for a component prop:

export default {
  name: 'ExampleComponent',
  props: [{
    prompt: {
      required: false,
      type: String,
      default: $t('example.prompt.default')
   }]
}

$t is obviously not in scope as shown, but it seems that at the point the default value for the prop is being evaluated, this is not the component itself either, so this.$t is also undefined.

What's the best way to use VueI18n to translate the default value for a prop?

2 Answers

You can access $t in a callback function as the callback is evaluated in the context of the created component.

prompt: {
  required: false,
  type: String,
  default: function () {
    this.$t('example.prompt.default')
  }
}

The downside here is that the value will be undefined in the beforeCreate life-cycle hook. If you need it there, then your best bet is to instead set the default value to the key of your i18n definition (example.prompt.default), and use this.$t(this.prompt) instead.

You can import the VueI18n instance from where you imported it.

import i18n from '../i18n'

export default {
  name: 'ExampleComponent',
  props: [{
    prompt: {
      required: false,
      type: String,
      default: i18n.t('example.prompt.default')
   }]
}

i18ns.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

function loadLocaleMessages () {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
  const messages = {}
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)
    if (matched && matched.length > 1) {
      const locale = matched[1]
      messages[locale] = locales(key)
    }
  })
  return messages
}

export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})

Related