# 基于vue-i18n的国际化实现方案

# 1.安装vue-i18n

npm install vue-i18n@next

# 2.创建以下目录及文件

生成目录结构 tree /f >project.txt

src
├─languages
│  │  index.ts
│  └─modules
│     en.ts
│     zh.ts

# 3、文件代码实例

  • index.ts
import { createI18n } from "vue-i18n";
import zh from "./modules/zh";
import en from "./modules/en";

const i18n = createI18n({
	legacy: false, // 如果要支持 compositionAPI,此项必须设置为 false
	locale: "zh", // 设置语言类型
	globalInjection: true, // 全局注册$t方法
	messages: {
		zh,
		en
	}
});

export default i18n;
  • en.ts 英
export default {
	header: {
		componentSize: "Component size",
		language: "Language",
		theme: "theme",
		layoutConfig: "Layout config",
		primary: "primary",
		darkMode: "Dark Mode",
		greyMode: "Grey mode",
		weakMode: "Weak mode",
		fullScreen: "Full Screen",
		exitFullScreen: "Exit Full Screen",
		personalData: "Personal Data",
		changePassword: "Change Password",
		logout: "Logout"
	}
	<!--...自行添加类header -->
};

  • zh.ts 中
export default {
	header: {
		componentSize: "组件大小",
		language: "国际化",
		theme: "全局主题",
		layoutConfig: "布局设置",
		primary: "primary",
		darkMode: "暗黑模式",
		greyMode: "灰色模式",
		weakMode: "色弱模式",
		fullScreen: "全屏",
		exitFullScreen: "退出全屏",
		personalData: "个人信息",
		changePassword: "修改密码",
		logout: "退出登录"
	}
}

# 4.main.ts中使用

 



 




// vue i18n
import I18n from "@/languages/index";

app.use(router)
	.use(I18n)
	.use(store)
	.use(ElementPlus)
	.mount('#app')

# 5.模板中使用

<template>
	<div>{{ $t("header.layoutConfig") }}</div>
</template>

<script lang="ts">
export default { name: "home" };
</script>
<script setup lang="ts">
import { useI18n } from "vue-i18n";
const { t } = useI18n();

console.log(t("header.layoutConfig")) // 布局设置
</script>
Last Updated: 3/27/2023, 11:06:07 PM