自定义国际化
1. 引入 vue-i18n
插件 pnpm install vue-i18n@next
2. 页面添加语言文件目录,添加自定义的语言文件
3.语言目录里添加 index.ts, 内容如下
import { createI18n } from "vue-i18n";// 自定义语言文件
import zhCN from "@/locales/zh-CN";
import en from "@/locales/en";const language = (navigator.language || 'en').toLocaleLowerCase() // 这是获取浏览器的语言
const i18n = createI18n({legacy: false, // 是否使用 composition API 模式locale: localStorage.getItem('locales') || language.split('-')[0] || 'zhCN', // 首先从缓存里拿,没有的话就用浏览器语言, "zhCN",fallbackLocale: 'zhCN', // 设置备用语言messages: {zhCN,en}
});export default i18n;
4. main.ts 中注册
import i18n from "./plugins/vueI18n";
app.use(i18n);
页面模板中可直接通过 $t('xxx')
来实现显示语言
5.修改语言 修改 vue-i18n 提供的 locale 变量
<script lang='ts' setup>
import { useI18n } from "vue-i18n";
const { locale } = useI18n({ useScope: "global" });
// 切换语言
const onMenuSelect = (key: string, keyPath: string[]) => {if (key == "lan-zh") {locale.value = "zhCN";saveLocales(locale.value);localsChangedNotify(locale.value);} else if (key == "lan-en") {locale.value = "en";saveLocales(locale.value);localsChangedNotify(locale.value);}
};
</script>
elementPlus 国际化
1. App.vue
使用 elementPlus 的 el-config-provider
进行最外层包裹
<template><el-config-provider :locale="locale"><router-view /></el-config-provider>
</template>
<script lang="ts" setup>import { onMounted, ref, computed } from "vue";import zhCn from "element-plus/es/locale/lang/zh-cn";
import en from "element-plus/es/locale/lang/en";import { languageSet } from "@/plugins/vueI18n";const language = ref(languageSet()); // 初始默认值
const locale = computed(() => (language.value === "zhCN" ? zhCn : en));// 监听语言的切换,设置 language 值,从而实现 elementPlus 组件语言的切换
window.addEventListener("onLocalsChanged", (e: any) => {language.value = e.detail;
});
</script>
2. 语言切换的地方,添加自定义事件派送
const localsChangedNotify = (value: string) => {const event = new CustomEvent("onLocalsChanged", { detail: value });window.dispatchEvent(event);
};// 切换语言
const onMenuSelect = (key: string, keyPath: string[]) => {if (key == "lan-zh") {locale.value = "zhCN";saveLocales(locale.value);localsChangedNotify(locale.value);} else if (key == "lan-en") {locale.value = "en";saveLocales(locale.value);localsChangedNotify(locale.value);}
};