Decrux
Decrux

Reputation: 207

Switching between languages VueI18n

I am using VueI18n for support of two languages in a website, build on VueJS, but now I want to switch between the two languages. Can you help me please?

main.js:

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import {messages} from './locales/bg_en_messages'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'en', // set locale
  messages // set locale messages
});

const app = new Vue({
  i18n,
  el: '#app',
  render: h => h(App),
  router
})

./locales/bg_en_messages.js:

export const messages = {
  bg: {
    labels: {
      personName: 'Име на лицето'
    }
  },
  en: {
    labels: {
      personName: 'Name of person'
    }
  }
}

VueJS:

<label>{{ $t("labels.personName") }}</label>

I want to put a dropdown menu or a button with which to switch between two languages. I was looking at the documentation for VueI18n, but there is not much information for it, so I will be grateful if you help me. :)

Updated post:

I made it working switching the languages. Now I have one more question about vue-good-table with vueI18n.

I have a table:

<template>
  <vue-good-table
    :columns="columns"
    :rows="items"
    :paginate="true"
    :lineNumbers="true">
  </vue-good-table>
</template>

columns: [
          {
            label: 'Column1',
            field: 'column1',
            type: 'String',
            filterable: true,
            placeholder: 'Column1'
          },
          {
            label: 'Column2',
            field: 'column2',
            type: 'String',
            filterable: true,
            placeholder: 'Column2'
          },
          {
            label: 'Column3',
            field: 'column3',
            type: 'String',
            filterable: true,
            placeholder: 'Column3'
          },
          {
            label: 'Column3',
            field: 'column3',
            type: 'String',
            filterable: true,
            placeholder: 'Column3'
          }
        ]

Can I somehow put in labels this {{ $t("label.column1") }} . For now label accepts only string, but I need to change the language of the columns too.

Upvotes: 2

Views: 4351

Answers (1)

Julien METRAL
Julien METRAL

Reputation: 1974

You can try as this following github issue to create a getter and a setter in your Vue instance :

app.i18n = new VueI18n({
    locale: 'es',
    fallbackLocale: 'es',
    messages
  })

  Object.defineProperty(Vue.prototype, '$locale', {
    get: function () {
      return app.i18n.locale
    },
    set: function (locale) {
      app.i18n.locale = locale
    }
  })

  // this part happens later

 new Vue(app)

And use it anywhere like that :

this.$locale // root Vuei18n locale    
this.$locale = 'en' // set root Vuei18n locale
// or
this.$root.i18n.locale // root Vuei18n locale    
this.$root.i18n.locale  = 'en' // set root Vuei18n locale

Upvotes: 3

Related Questions