Vue3 i18n best practice
Recently, I’ve been working on a front-end project with i18n support, and I’d like to note the steps here.
Step 1: Install dependency
1 |
|
As of now, we have no other choice.
Step 2: Create Language Packs
At first, we need to define what a language pack contains:
1 |
|
Secondly, create our language pack:
1 |
|
At last, store all of them in a single file:
1 |
|
Step 3: Use in Vue SFC
At this point, you have only defined the language pack, to use it you need to register the plugin first:
1 |
|
Note the locales
here, where you need to define the logic for selecting language packs. As my requirements here are simple, use Chinese when the user language is Chinese, otherwise always use English, in many cases this is not enough and you need to customize your logic yourself.
Use the Vue plugin:
1 |
|
Now you can use $t()
in the Vue template to get the string for the current language:
1 |
|
It will be rendered as:
1 |
|
However not all the text is defined in the template, this is not enough.
Step 4: Use in TypeScript
Edit src/util/i18n.ts
:
1 |
|
Usage:
1 |
|
All done. Enjoy your i18n-ready application!