How to store strings for translation in Vue project

Tags: , , , ,



I want to use two Languages in my application – so i want a dictionary like string file (kinda like in android development) where i simply store my strings with id’s and can access the strings easily by id perhaps with a parameter for my language. What kind of file is easy to parse in my vue components and is suitable for my use case?

Answer

You can use normal js file and exporting normal object containing the strings.

However I highly recommended you to use vue-i18n instead.

Install: npm install vue-i18n

or if you are using Vue Cli, run: vue add i18n

Quick usage:

// If using a module system (e.g. via vue-cli), import Vue and VueI18n and then call Vue.use(VueI18n).
// import Vue from 'vue'
// import VueI18n from 'vue-i18n'
//
// Vue.use(VueI18n)

// Ready translated locale messages
const messages = {
  en: {
    message: {
      hello: 'hello world'
    }
  },
  ja: {
    message: {
      hello: 'ã“ã‚“ã«ã¡ã¯ã€ä¸–ç•Œ'
    }
  }
}

// Create VueI18n instance with options
const i18n = new VueI18n({
  locale: 'ja', // set locale
  messages, // set locale messages
})

Then on your template

<p> {{ $t("message.hello") }} </p>


Source: stackoverflow