文章目录
- 1. 在项目中创建一个国际化插件的文件i18n.ts
- 2. 创建语言模块json
- 3. 注册插件
- 4. 语言切换组件
- 5. 使用插件(ts中使用全局需注意点)
1. 在项目中创建一个国际化插件的文件i18n.ts
<!-- plugins/i18n.ts -->
export const i18nPlugin = {install(app: any, option: any) {app.config.globalProperties.$t = (key: string) => {return key.split(".").reduce((o, k) => {if (o) return o[k];}, option[localStorage.getItem("language") || "zhCN"]);} }
}
2. 创建语言模块json
<!-- assets/i18n/zh-CN.json -->
{"project": {"projectName": "项目名称"}
}
<!-- assets/i18n/en-US.json -->
{"project": {"projectName": "project name"}
}
3. 注册插件
import zhCN from "./assets/i18n/zh-CN.json";
import enUS from "./assets/i18n/en-US.json";
import { i18nPlugin } from "./plugins/i18n";const app = createApp(App);
app.use(i18nPlugin, {zhCN,enUS,
});
4. 语言切换组件
<!-- components/ChangeLanguage.vue -->
<template><a-select:value="language"@change="changeLanguage"><a-select-option value="zhCN">中文</a-select-option><a-select-option value="enUS">English</a-select-option></a-select>
</template><script lang="ts"setup>
import {ref} from "vue";
const language = ref(localStorage.getItem("language") || "zhCN");
const changeLanguage = (value: string) => {language.value = value;localStorage.setItem("language", value);window.location.reload();
};
</script>
5. 使用插件(ts中使用全局需注意点)
<template><ChangeLanguage />
</template>
<!-- component.vue -->
<script lang="ts" setup>
import { getCurrentInstance } from "vue";
import SelectLanguage from "@/components/SelectLanguage.vue";
const instance = getCurrentInstance();
const $t = instance?.appContext.app.config.globalProperties.$t;
const translatedText = $t('project.projectName');
console.log(translatedText);
</script>