Introduction
Recently I been ask to implement i18n into our company’s web app. The library we use is Vue-i18n. I’ll share with you how to implement this library with your app.
Instruction
i18n setup
- Install the package
1 | npm install vue-i18n --save |
- Create lang folder to store your json file and Vue-i18n setup
1 | // Folder Structure |
- Create a message and locale variable
- locale variable stores the current locale that you wish to display
- messages varaibles stores all the language package (en.json, cn.json)
- Store messages and locale in your VueI18n instance
1 | Vue.use(VueI18n) |
Vuex Setup
- In our main.js (where we handle all our imports), we want to export our Vue instance as a variable
1 | // main.js |
- Now we can import our Vue instance as app variable and use it in our vuex to access our i18n to change locale
1 | // mutation.js |
- In our Vue component, we can map our vuex action.
- Finally, all we need to do is to connect our directive with :click directive
1 | <button @click="setLang('cn')">cn</button> |
1 | methods: { |
Debug Technique
- Set vue instance and vuex store as window variable, so we can ccess your i18n in your chrome
1 | //main.js |
Edit 2017.10.07
How to use lazy loading (or dynamic locale ) in vue i18n.
You want use lazy loading becuase you don’t want to load all the language pack in the initial load. It will make your bundle size bigger and slow down your app.
Here’s how you use it in your app.
1 | async setLangNew({commit}, payload){ |
Recommendations
If you are interested in learning Vue or Advanced Javascript, I strongly recommend these 2 courses.👊
🏷 Vue 2 The Complete Guide: http://bit.ly/udemyvue
🏷 Modern JavaScript From The Beginning: http://bit.ly/modernjavascript
👍USE THE BOTTOM LINK TO GET ADDIONIONAL DISCOUNT ON YOUR COURSES👍
http://bit.ly/udemy10tw
http://bit.ly/udemy10limited