feat(i18n): 引入 routeI18nInstance 以支持路由菜单标题的多语言处理
All checks were successful
CI/CD Pipeline / playwright (push) Successful in 5m9s
CI/CD Pipeline / build-and-deploy (push) Successful in 2m48s

This commit is contained in:
严浩
2025-11-03 15:03:22 +08:00
parent b4fcde324d
commit f9f82e4d29
6 changed files with 49 additions and 25 deletions

View File

@@ -2,7 +2,9 @@
* All i18n resources specified in the plugin `include` option can be loaded
* at once using the import syntax
*/
import { router } from '@/plugins/00.router-plugin';
import messages from '@intlify/unplugin-vue-i18n/messages';
import { createGetRoutes } from 'virtual:meta-layouts';
import { createI18n } from 'vue-i18n';
@@ -26,6 +28,44 @@ export const i18nInstance = createI18n({
messages,
});
watchEffect(() => {
locale.value = i18nInstance.global.locale.value;
export const routeI18nInstance = createI18n({
legacy: false, // you must set `false`, to use Composition API
locale: locale.value,
inheritLocale: true,
useScope: 'local',
missing: (locale, key) => {
consola.warn(`菜单翻译缺失: locale=${locale}, key=${key}`);
return key;
},
fallbackRoot: true,
messages: i18nRouteMessages,
});
watchEffect(
() => {
locale.value = i18nInstance.global.locale.value;
},
{ flush: 'sync' },
);
watch(
() => i18nInstance.global.locale.value,
() => {
routeI18nInstance.global.locale.value = i18nInstance.global.locale.value;
const routes = createGetRoutes(router)(); // 获取路由表但是不包含布局路由
routes.forEach((route) => {
const { t, te } = routeI18nInstance.global;
if (router.currentRoute.value.name) {
router.currentRoute.value.meta.title = t(router.currentRoute.value.name as string);
}
route.meta = route.meta || {};
const routeName = route.name as string;
route.meta.title = te(routeName) ? t(routeName) : routeName;
});
},
{ immediate: true, flush: 'sync' },
);

View File

@@ -1,7 +1,7 @@
import type { I18nOptions } from 'vue-i18n';
const modules = import.meta.glob(['./*.ts', '!./route-messages-auto-imports'], {
eager: true,
eager: true /* true 为同步false 为异步 */,
import: 'default',
});