默认中文状态如下图:
英文状态如下图:
1.安装指定版本npm install vue-i18n@8
2.在src目录下新建如下图文件夹和文件
在index.js中配置如下代码:
import Vue from "vue";
import VueI18n from "vue-i18n";
import elementEnLocale from "element-ui/lib/locale/lang/en"; // element-ui lang导入Element的语言包 英文
import elementZhLocale from "element-ui/lib/locale/lang/zh-CN"; // element-ui lang g导入Element的语言包 中文
import enLocale from "./en"; // 导入项目中用到的英文语言包
import zhLocale from "./zh"; // 导入项目中用到的中文语言包
import ElementLocale from "element-ui/lib/locale";
Vue.use(VueI18n);
const messages = {
en: {
...enLocale,
...elementEnLocale,
},
zh: {
...zhLocale,
...elementZhLocale,
},
};
const i18n = new VueI18n({
locale: localStorage.getItem("language") || "zh", // 设置语种
messages, // 设置全局当地语言包,
fallbackLocale: "zh",
numberFormats: {
//设置 数字本地化
en: {
currency: {
//添加 $
style: "currency",
currency: "USD",
},
},
zh: {
currency: {
//添加 ¥
style: "currency",
currency: "JPY",
currencyDisplay: "symbol",
},
},
},
dateTimeFormats: {
//设置 日期时间本地化
en: {
short: {
year: "numeric",
month: "short",
day: "numeric",
},
long: {
year: "numeric",
month: "short",
day: "numeric",
weekday: "short",
hour: "numeric",
minute: "numeric",
},
},
zh: {
short: {
year: "numeric",
month: "short",
day: "numeric",
},
long: {
year: "numeric",
month: "short",
day: "numeric",
weekday: "short",
hour: "numeric",
minute: "numeric",
},
},
},
});
ElementLocale.i18n((key, value) => i18n.t(key, value));
export default i18n;
zh.js和en.js里面的内容根据自己需求来配置
//zh.js
export default {
common: {
username: '用户名',
password: '密码',
save: '保存',
edit: '编辑',
update: '更新',
delete: '删除',
forever: '永久',
expired: '过期',
message:"消息"
},
lang:'语言切换展示区域',
cz:'操作',
Login:'登录',
Welcome:'欢迎',
User:'用户',
User2:'用户2',
}
//en.js
export default {
common: {
username: 'username',
password: 'password',
save: 'Save',
edit: 'Edit',
update: 'Update',
delete: 'Delete',
forever: 'Forever',
expired: 'Expired',
message:"message",
},
lang:'Language switching display area',
cz:'operate',
Login:'login',
Welcome:'welcome',
User:'yh',
User2:'yh2',
}
3.完成以上两步之后,在main.js里面引入
4.页面中使用
5.切换语言的逻辑
<el-dropdown @command="handleSetLanguage">
<span class="el-dropdown-link">
{{$i18n.locale=='zh' ? '中文' :'英文'}}<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="zh" :disabled="$i18n.locale=='zh'">中文</el-dropdown-item>
<el-dropdown-item command="en" :disabled="$i18n.locale=='en'">英文</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<script>
handleSetLanguage(lang) {
this.$i18n.locale = lang;
sessionStorage.setItem('language',lang)
console.log(this.$i18n);
// 修改页面标题,还需在路由里面配置
this.$nextTick(()=>{
document.title = this.$t(this.$route.name)
})
},
</script>
修改页面标题
router.js里面添加name属性(在语言包里面把name做为属性名去配置对应的属性值)
前置路由守卫里面去获取设置给document.title