安装包
yarn add vue-i18n
配置
根目录新增language
文件夹,创建index.ts
、ch.js
、en.js
、jp.js
// index.ts
import { createI18n } from "vue-i18n"
export default createI18n({
locale: localStorage.getItem("language") || "ch",
messages: {
ch: require("./ch"),
en: require("./en"),
jp: require("./jp")
}
})
配置文件以
.js
结尾是因为ts
和js
的模块导入和导出方式不同,为了方便就用.js
了
// ch.js
module.exports = {
menu: {
home: "主页",
system: "系统管理",
user: "用户管理",
role: "角色管理"
},
}
其余两个文件结构相同
注入
// main.ts
// ....
import I18n from "./lang/index"
app.use(I18n);
使用
<template>
<div>{{ $t("menu.home") }}</div>
</template>
// 在混合API中的使用
import { useI18n } from "vue-i18n";
setup() {
const { t } = useI18n();
console.log(t("menu.home"))
}
// 在JS中的使用
import I18n from "../lang/index"
console.log(I18n.global.t("menu.home"))
切换
import { getCurrentInstance} from "vue"
{
const { proxy } = getCurrentInstance() as any; // 获取this对象
proxy.$i18n.locale = "en";
}