Hypefactors
Published in

Hypefactors

Add i18n and manage translations of a Vue.js powered website

Vue + Vue Router + Vue-i18n + Lokalise.co

TLDR:

Initial setup

  1. Instantiate the plugin by providing a default locale, a fallback and an object containing all the translation strings.
Setup i18n
Pass i18n instance to Vue app

Changing the language

this.$i18n.locale = 'fr'
Simple language switcher

Setting the language as a route parameter

  1. Check if the URL contains the language parameter
  2. Check if the language is supported by the app. If not redirect to a supported one.
  3. Check if the language in the param is the default one. Don’t do nothing if it is.
  4. (Optional) async load the language strings
  5. Change the language in the App

Making it work with Vue Router

Setup routes file
Instantiate Router
Pass router instance to App
  1. the route you want to go to — to
  2. the one you come from — from
  3. callback to call when you are done — next
Initial Router guard

Async loading translation strings

  • Load the translation strings on demand (async)
  • Feed the strings into Vue-i18n
Async load json files
Separate language files

Using vue-i18n outside Vue components

  • Vuex store
  • Route guards
  • beforeRouteEnter Vue hooks — the Vue instance is not not ready yet, so you can’t use this there.

Cleaning it up

Bonus: Managing translation strings using Lokalise

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store