Skip to content

国际化

y9 组件默认使用简体中文,如果你希望使用其他语言,你可以参考下面的方案

WARNING

注意: 以下方案适用于最新的y9plugin-components-auto,如果还是旧版本的y9plugin-components,仅需要参考第一步骤配置即可

第一步: 在 main.ts 文件配置语言包传入 y9 组件

js
import { createApp } from "vue";
import { setupStore } from "@/store";
import y9pluginComponents from "y9plugin-components-auto";
import y9_zhCn from 'y9plugin-components-auto/dist/locale/zh-cn.mjs';
import y9_en from 'y9plugin-components-auto/dist/locale/en.mjs';
import { useSettingStore } from "@/store/modules/settingStore";
const app: any = createApp(App);
setupStore(app);
let opts = ref({}); //y9组件选项配置
watch(
  () => useSettingStore().getWebLanguage, //监听语言变化,配置对应的语言包
  (newLang) => {
    opts.value.locale = newLang === "en" ? y9_en : y9_zhCn;
  },
  {
    immediate: true,
  }
);
app.use(y9pluginComponents, opts.value);
app.mount("#app");

第二步: 在 App.vue 文件配置语言包,让element-plus组件响应语言变化

vue
<script lang="ts" setup>
//y9组件语言包
import y9_zhCn from 'y9plugin-components-auto/dist/locale/zh-cn.mjs';
import y9_en from 'y9plugin-components-auto/dist/locale/en.mjs';
//框架的store
import { useSettingStore } from "@/store/modules/settingStore";
const settingStore = useSettingStore();

// 获取element-plus组件的当前语言设置
const currentLocale = ref({
    name: 'zh-cn',
    el: y9_zhCn.el
});
watch(
    () => useSettingStore().getWebLanguage, //监听语言变化,传入对应的语言包
    (newLang) => {
        currentLocale.value =
                      newLang === 'en' ? { name: 'en', el: y9_en.el } : { name: 'zh-cn', el: y9_zhCn.el };
    },
    {
        immediate: true,
    }
);
</script>

<template>
    <el-config-provider :locale="currentLocale">
        <router-view />
    </el-config-provider>
</template>

扩展: 合并项目内的语言包,实现项目范围内,自定义语言文案【参考示例】

vue
<script lang="ts" setup>
//y9组件语言包
import y9_zhCn from 'y9plugin-components-auto/dist/locale/zh-cn.mjs';
import y9_en from 'y9plugin-components-auto/dist/locale/en.mjs';
// 引入项目内的语言包【示例】
import en from '@/locales/en.json';
import zhCn from '@/locales/zh-cn.json';
//框架的store
import { useSettingStore } from "@/store/modules/settingStore";
const settingStore = useSettingStore();
// 合并项目内的语言包
const mergedEn = { ...y9_en, ...en };
const mergedZhCn = { ...y9_zhCn, ...zhCn };
// 监听语言变化,切换合并后的语言包
watch(
    () => useSettingStore().getWebLanguage,
    (newLang) => {
        currentLocale.value =
                      newLang === 'en' ? { name: 'en', el: mergedEn } : { name: 'zh-cn', el: mergedZhCn };
    },
    {
        immediate: true,
    }
);
</script>

<template>
    <el-config-provider :locale="currentLocale">
        <router-view />
    </el-config-provider>
</template>

Released under the GPL-3.0 License.