Dynamic localization in vue-i18n

4.7k views Asked by At

I would like to update my localization messages in vue-i18n dynamically.

I am building a webshop, where every item has descriptions in more languages. So what I’d like to achieve is when I get the webshop items from the REST API I want to put their names, descriptions etc. to the messages object in vue-i18n so it can work with them. Does the vue-i18n API have something to handle that? Also I am getting the data from the server (I get a Promise), so how can I make sure it gets updated in the browser view, when I finally get the response, and add the data to the localization?

1

There are 1 answers

0
godzsa On BEST ANSWER

What I did was write a mixin, and use it everywhere I need dynamic localization:

export default {
  methods: {
    $t: function (translate) {
      if (typeof translate === 'string') {
        return this.$i18n.t(translate)
      } else if (translate === void 0) {
        return this.$i18n.t('loading')
      }
      return translate[this.$i18n.locale]
    }
  }
}

This way when my texts look like the following, I can call $t(text) (NOT $t('text') of course):

data: function () {
   return {text: {en:'Book', de:'Buch', hu:'Könyv'}}
}

So in your components you have to import this and add it as a mixin:

import dynamicLocalization from '@/components/mixins/dynamic-localization'

export default {
   ...
   mixins:[dynamicLocalization]
   ...
}