一、安装
如果是vue2直接安装8.2.1版本,否则会出现版本不匹配的错误
npm install vue-i18n@8.2.1 --save
二、文件编辑
在src目录下创建文件
分别创建文件内容
,内容为需要翻译的字段
- en.js
export const h = {
system: "Background management system",
loginOut:"LoginOut",
LayoutSet:'Layout settings',
LanguageSwitch:'Language switching',
PersonalCenter:'Personal Center',
homePage:'Home Page'
}
- zh.js
export const h = {
system: "后台管理",
loginOut:"退出登录",
LayoutSet:'布局设置',
LanguageSwitch:'语言切换',
PersonalCenter:'个人中心',
homePage:'首页'
}
- index.js
import Vue from "vue";
import VueI18n from "vue-i18n";
//配合element
import ElementLocale from 'element-ui/lib/locale'
import zhLocale from "element-ui/lib/locale/lang/zh-CN"
import enLocale from "element-ui/lib/locale/lang/en"
//引入语言包
const zh=require("./lan/zh")
const en = require( "./lan/en" )
// import zh from './lan/zh'
Vue.use(VueI18n); // 全局挂载
export const i18n = new VueI18n({
locale: localStorage.getItem("lang") || "zh", // 从localStorage中获取 默认英文
messages: {
zh: {
...zh,
...zhLocale
}, // 中文语言包
en: {
...en,
...enLocale
} // 英文语言包
}
})
//element需要
ElementLocale.i18n((key, value) => i18n.t(key, value))
//如果需要在js文件中使用,需要下面的方法
export const translate = (localeKey) => {
const locale = localStorage.getItem("lang") || "zh"
const hasKey = i18n.te(localeKey, locale) // 使用i18n的 te 方法来检查是否能够匹配到对应键值
const translatedStr = i18n.t(localeKey)
if (hasKey) {
return translatedStr
}
return localeKey
}
export default i18n;
- main.js
import { i18n } from './i18n/index'
new Vue({
el: '#app',
i18n,
router,
store,
render: h => h(App)
})
- router.js
import { translate as $t } from "@/i18n"