Skip to content
Advertisement

How to store strings for translation in Vue project

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?

Advertisement

Answer

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

However I highly recommend 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>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement