1. Download the dependency package
npm install vue-i18n --save
2. Create a new folder i18n under the src directory in the project , and create a new folder langs under it , which stores various language js files, such as en.js , zh_CN.js
The internal file structure is:
/**zh.js文件**/
module.exports = {
menu : {
home:"首页"
},
content:{
main:"这里是内容"
}
}
/**en.js文件**/
module.exports = {
menu : {
home:"home"
},
content:{
main:"this is content"
}
}
src/i18n/i18n.js
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import zh_CN from './langs/zh_CN/zh_CN';
import en_US from './langs/en/en_US';
import enLocale from 'element-ui/lib/locale/lang/en';
import zhLocale from 'element-ui/lib/locale/lang/zh-CN';
Vue.use(VueI18n);
const messages = {
en_US: {
...en_US,
...enLocale,
},
zh_CN: {
...zh_CN,
...zhLocale,
},
};
const i18n = new VueI18n({
locale: localStorage.lang || 'zh_CN',
messages,
});
export default i18n;
3. Configuration in main.js
import i18n from './i18n/i18n'; //i18n国际化
Vue.use(Element, {
i18n: (key, value) => i18n.t(key, value), //i18n国际化
});
window.vm = new Vue({
el: '#app',
i18n, //i18n国际化
router,
store,
render: (h) => h(App),
});
4. Page usage
//页面内
{
{$t('system.cancel'}}
window.vm.$i18n.t('system.cancel')
//js
this.$t('system.cancel')
5. Notes:
Match custom content in internationalized copy
this.$t('validate.range_length', ['5', '20']) //Please enter characters whose length is between {0} and {1} Change 0-1 to 5-20
6. Add settings to display Chinese in the VSCode code editor in real time:
Add in setting.json in the .vscode folder of the project root directory
{
"i18n-ally.localesPaths": ["src/i18n/langs"],
"i18n-ally.enabledParsers": ["json", "js"], //这个最好加上,如果是其他格式,如ts,不加上就无效了
"i18n-ally.keystyle": "nested", // 翻译路径格式,
"i18n-ally.sourceLanguage": "en", // 翻译源语言
"i18n-ally.displayLanguage": "zh_CN" //显示语言, 这里也可以设置显示英文为en,
// "i18n-ally.extract.keygenStrategy": "random", // 翻译字段命名采用随机字符 枚举['slug','random','empty']
// "i18n-ally.extract.keygenStyle": "camelCase", // 翻译字段命名样式采用驼峰
}