Search code examples
javascriptvue.jsvue-i18n

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


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?


Solution

  • 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.