前端日期组件国际化支持方案

在 oinone 平台中,系统默认支持基础的国际化翻译功能。但由于日期时间组件的国际化依赖对应语言包,而全量引入语言包会显著增加打包体积,因此前端默认仅集成了中、英文的日期时间支持。若需为日期时间组件扩展其他语言(如日语)的国际化支持,需手动导入对应语言包并完成配置,具体步骤如下:

前端日期组件国际化支持方案
前端日期组件国际化支持方案

假设我们现在国际化翻译切换成了日语,那么我们在日期时间也要支持日语,那么需要如下操作:

1: 重写 RootWidget

继承平台默认的 RootWidget,SPI 注册条件保持跟平台一致即可覆盖平台默认的RootWidget

// CustomRootWidget.ts

import { RootComponentSPI, RootWidget, SPIFactory } from '@oinone/kunlun-dependencies';
import Root from './Root.vue';

// 通过SPI注册覆盖平台默认的root组件
@SPIFactory.Register(RootComponentSPI.Token({ widget: 'root' }))
export class CustomRootWidget extends RootWidget {
  public initialize() {
    super.initialize();
    this.setComponent(Root);
    return this;
  }
}

2: 覆盖 Root 组件的 Vue 文件

自定义的 Vue 文件需负责导入目标语言(如日语)的语言包,并根据当前语言环境动态切换配置。这里需要同时处理 ant-design-vue、element-plus 组件库及 dayjs 工具的语言包,确保日期组件的展示和交互统一适配目标语言。

<!-- Root.vue -->
<template>
  <a-config-provider :locale="antLocale">
    <el-config-provider :locale="eleLocale">
      <match :rootToken="root">
        <template v-for="page in pages" :key="page.widget">
          <route v-if="page.widget" :path="page.path" :slotName="page.slotName" :widget="page.widget">
            <slot :name="page.slotName" />
          </route>
        </template>

        <route :path="pagePath" slotName="page" :widgets="{ page: widgets.page }">
          <slot name="page" />
        </route>

        <route path="/" slotName="homePage">
          <slot name="homePage" />
        </route>
      </match>
    </el-config-provider>
  </a-config-provider>
</template>

<script lang="ts">
import { CurrentLanguage, EN_US_CODE, UrlHelper, ZH_CN_CODE } from '@oinone/kunlun-dependencies';
import { ConfigProvider as AConfigProvider } from 'ant-design-vue';
import { ElConfigProvider } from 'element-plus';
import dayjs from 'dayjs';

// 导入ant-design-vue语言包
import enUS from 'ant-design-vue/es/locale/en_US';
import zhCN from 'ant-design-vue/lib/locale/zh_CN';
import jaJP from 'ant-design-vue/lib/locale/ja_JP'; // 新增:日语语言包

// 导入 dayjs的语言包
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/ja'; // 新增:日语语言包

// 导入element-plus语言包
import elEn from 'element-plus/dist/locale/en.mjs';
import elZhCn from 'element-plus/dist/locale/zh-cn.mjs';
import elJaJP from 'element-plus/dist/locale/ja.mjs'; // 新增:日语语言包

import { computed, defineComponent, onMounted, onUnmounted, ref } from 'vue';

export default defineComponent({
  components: { AConfigProvider, ElConfigProvider },
  props: ['widgets', 'loginUrl', 'root', 'pages'],
  inheritAttrs: false,
  setup() {
    const pagePath = computed(() => UrlHelper.append(UrlHelper.absolutePath(process.env.BASE_PATH), 'page'));

    const locale = ref(zhCN.locale); // 初始化语言环境变量(默认中文)
    const antLocale = ref(zhCN); // ant-design-vue的语言配置
    const eleLocale = ref(elZhCn); // element-plus的语言配置

    const refreshLocale = (languageCode: string) => {
      switch (languageCode) {
        case ZH_CN_CODE: // 中文
          locale.value = zhCN.locale;
          antLocale.value = zhCN;
          eleLocale.value = elZhCn;
          break;
        case EN_US_CODE: // 英文
          locale.value = enUS.locale;
          antLocale.value = enUS;
          eleLocale.value = elEn;
          break;
        case 'jp-JP': // 新增:日语判断
          locale.value = jaJP.locale;
          antLocale.value = jaJP;
          eleLocale.value = elJaJP;
          break;
        default:
          locale.value = zhCN.locale;
          break;
      }

      // 更新dayjs的全局语言配置
      dayjs.locale(locale.value);
    };

    onMounted(() => {
      refreshLocale(CurrentLanguage.getCodeByLocalStorage());
      CurrentLanguage.onRefreshLocalStorage(refreshLocale);
    });

    onUnmounted(() => {
      CurrentLanguage.clearOnRefreshLocalStorage(refreshLocale);
    });

    return {
      zhCN,
      enUS,
      elZhCn,
      elEn,
      locale,
      pagePath,
      antLocale,
      eleLocale
    };
  }
});
</script>

3: 处理动态弹窗的国际化(特殊场景)

若业务中使用executeViewAction动态打开弹窗,弹窗内的日期组件可能无法继承全局语言配置,因此需额外重写 DialogContainerWidget 以确保弹窗内的语言环境一致。

3.1 重写 DialogContainerWidget 类

import { DialogContainerWidget, RootComponentSPI, SPIFactory } from '@oinone/kunlun-dependencies';
import Dialog from './Dialog.vue';

// 注册自定义弹窗容器,覆盖默认组件
@SPIFactory.Register(RootComponentSPI.Token({ widget: 'dialog-container' }))
export class CustomDialogContainerWidget extends DialogContainerWidget {
  public initialize(props) {
    super.initialize(props);
    this.setComponent(Dialog);
    return this;
  }
}
<template>
  <a-config-provider :locale="antLocale">
    <el-config-provider :locale="eleLocale">
      <slot />
    </el-config-provider>
  </a-config-provider>
</template>

<script lang="ts">
import { ConfigProvider as AConfigProvider } from 'ant-design-vue';
import dayjs from 'dayjs';
import { ElConfigProvider } from 'element-plus';
import { defineComponent, onMounted, ref } from 'vue';

// 导入ant-design-vue语言包
import enUS from 'ant-design-vue/es/locale/en_US';
import zhCN from 'ant-design-vue/lib/locale/zh_CN';
import jaJP from 'ant-design-vue/lib/locale/ja_JP'; // 日语

// 导入 dayjs的语言包
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/ja'; // 日语

// 导入element-plus语言包
import elEn from 'element-plus/dist/locale/en.mjs';
import elZhCn from 'element-plus/dist/locale/zh-cn.mjs';
import elJaJP from 'element-plus/dist/locale/ja.mjs'; // 日语
import { EN_US_CODE, ZH_CN_CODE } from '@oinone/kunlun-vue-ui-antd';

export default defineComponent({
  components: { AConfigProvider, ElConfigProvider },
  inheritAttrs: false,
  setup() {
    const locale = ref(zhCN.locale);
    const antLocale = ref(zhCN);
    const eleLocale = ref(elZhCn);
    onMounted(() => {
      const lang = localStorage.getItem('language') || ('zh-CN' as any);
      switch (lang) {
        case ZH_CN_CODE:
          locale.value = zhCN.locale;
          antLocale.value = zhCN;
          eleLocale.value = elZhCn;
          break;
        case EN_US_CODE:
          locale.value = enUS.locale;
          antLocale.value = enUS;
          eleLocale.value = elEn;
          break;
        case 'jp-JP': // 新增日语判断
          locale.value = jaJP.locale;
          antLocale.value = jaJP;
          eleLocale.value = elJaJP;
          break;
        default:
          locale.value = zhCN.locale;
          break;
      }
      dayjs.locale(locale.value);
    });

    return {
      zhCN,
      enUS,
      elZhCn,
      elEn,
      locale,
      antLocale,
      eleLocale
    };
  }
});
</script>

通过上述步骤,可实现 oinone 平台日期组件对新增语言(如日语)的国际化支持。核心逻辑是:通过重写全局配置组件引入目标语言包,并根据当前语言环境动态切换组件库和工具的语言配置;对于动态弹窗等特殊场景,需额外处理其容器组件以确保语言环境一致。

若需扩展其他语言(如韩语、法语等),只需参照上述步骤,替换对应的语言包并在 switch 逻辑中添加对应判断即可。

Oinone社区 作者:汤乾华原创文章,如若转载,请注明出处:https://doc.oinone.top/frontend/21519.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
汤乾华的头像汤乾华数式员工
上一篇 2025年7月21日 pm8:49
下一篇 2025年8月14日 pm5:55

相关推荐

  • 【前端】默认布局模板(v4)

    默认母版(Mask) PC端默认母版 <mask> <multi-tabs /> <header> <widget widget="app-switcher" /> <block> <widget widget="notification" /> <widget widget="divider" /> <widget widget="language" /> <widget widget="divider" /> <widget widget="user" /> </block> </header> <container> <sidebar> <widget widget="nav-menu" height="100%" /> </sidebar> <content> <breadcrumb /> <block width="100%"> <widget width="100%" widget="main-view" /> </block> </content> </container> </mask> PC端默认内联Tabs母版(<multi-tabs inline="true" />) <mask> <header> <widget widget="app-switcher" /> <block> <widget widget="notification" /> <widget widget="divider" /> <widget widget="language" /> <widget widget="divider" /> <widget widget="user" /> </block> </header> <container> <sidebar> <widget widget="nav-menu" height="100%" /> </sidebar> <block height="100%" flex="1 0 0" flexDirection="column" alignContent="flex-start" flexWrap="nowrap" overflow="hidden"> <multi-tabs inline="true" /> <content> <breadcrumb /> <block width="100%"> <widget width="100%" widget="main-view" /> </block> </content> </block> </container> </mask> 移动端默认母版 <mask> <widget widget="user" /> <widget widget="nav-menu" app-switcher="true" menu="true" /> <widget widget="main-view" height="100%" /> </mask> PC端默认布局(Layout) 表格视图(TABLE) <view type="TABLE"> <pack widget="group"> <view type="SEARCH"> <element widget="search" slot="search" /> </view> </pack> <pack widget="group" slot="tableGroup"> <element widget="actionBar" slot="actionBar"> <xslot name="actions" /> </element> <element widget="table" slot="table"> <element widget="expandColumn" slot="expandRow" /> <xslot name="fields" /> <element widget="rowActions" slot="rowActions" /> </element> </pack> </view> 表单视图(FORM) <view type="FORM"> <element widget="actionBar" slot="actionBar"> <xslot name="actions" /> </element> <element widget="form" slot="form"> <xslot name="fields" /> </element> </view>…

    2023年11月1日
    1.4K01
  • 前端自定义组件之左右滑动

    本文将讲解如何通过自定义,实现容器内的左右两个元素,通过左右拖拽分隔线,灵活调整宽度。其中左右元素里的内容都是界面设计器拖出来的。 实现路径 1. 界面设计器拖出页面 我们界面设计器拖个布局容器,然后在左右容器里拖拽任意元素。完成后点击右上角九宫格,选中布局容器,填入组件 api 名称,作用是把布局容器切换成我们自定义的左右滑动组件,这里的 api 名称和自定义组件的 widget 对应。最后发布页面,并绑定菜单。 2. 组件实现 widget 组件重写了布局容器,核心函数 renderLeft、renderRight,通过 DslRender.render 方法渲染界面设计器拖拽的元素。 import { BasePackWidget, DefaultContainersWidget, DslDefinition, DslRender, SPI, Widget } from '@oinone/kunlun-dependencies'; import LeftRightSlide from './LeftRightSlide.vue'; // 拿到界面设计器配置的子容器元素 function fetchContainerChildren(widgets?: DslDefinition[], level = 3): DslDefinition[] { if (!widgets) { return []; } const children: DslDefinition[] = []; for (const widget of widgets) { if (widget.widget === 'container') { children.push(widget); } else if (level >= 1) { fetchContainerChildren(widget.widgets, level – 1).forEach((child) => children.push(child)); } } return children; } @SPI.ClassFactory(BasePackWidget.Token({ widget: 'LeftRightSlide' })) export class LeftRightSlideWidget extends DefaultContainersWidget { public initialize(props) { super.initialize(props); this.setComponent(LeftRightSlide); return this; } // 获取容器的子元素 public get containerChildren(): DslDefinition[] { return fetchContainerChildren(this.template?.widgets); } // 初始宽度配置 @Widget.Reactive() public get initialLeftWidth() { return this.getDsl().initialLeftWidth || 400; } // 最小左宽度配置 @Widget.Reactive() public get minLeftWidth() { return this.getDsl().minLeftWidth || 200; } // 最小右宽度配置 @Widget.Reactive() public get minRightWidth() { return this.getDsl().minRightWidth || 200; } // 根据容器子元素渲染左侧 @Widget.Method() public renderLeft() { // 把容器的第一个元素作为左侧 const containerLeft = this.containerChildren[0]; if (containerLeft) { return DslRender.render(containerLeft); } } // 根据容器子元素渲染右侧 @Widget.Method() public renderRight() { // 把容器的第二个元素作为右侧 const containerRight = this.containerChildren[1]; if…

    2025年7月8日
    4.4K00
  • 如何增加页面消息通知轮询的间隔或者关闭轮询

    场景 oinone的前端页面默认自带了消息通知功能,在顶部状态栏可以看到消息的查看入口,默认每隔5秒查询一次最新的消息,我们可以通过自定义消息组件增加该间隔或者是关闭轮询 示例代码 修改轮询间隔 import { MaskWidget, NotificationWidget, SPI } from '@kunlun/dependencies'; @SPI.ClassFactory(MaskWidget.Token({ widget: 'notification' })) export class DemoNotificationWidget extends NotificationWidget { /** * 轮询间隔时间,单位: 秒 * @protected */ protected msgDelay = 30000; } 关闭轮询 import { MaskWidget, NotificationWidget, SPI } from '@kunlun/dependencies'; @SPI.ClassFactory(MaskWidget.Token({ widget: 'notification' })) export class DemoNotificationWidget extends NotificationWidget { protected mounted() { super.mounted(); // 清除轮询的定时器 this.msgTimer && clearInterval(this.msgTimer); // 挂载后手动查询一次消息 this.getMsgTotal(); } }

    2024年8月20日
    1.5K00
  • 后端:如何自定义表达式实现特殊需求?扩展内置函数表达式

    平台提供了很多的表达式,如果这些表达式不满足场景?那我们应该如何新增表达式去满足项目的需求?目前平台支持的表达式内置函数,参考 1. 扩展表达式的场景 注解@Validation的rule字段支持配置表达式校验如果需要判断入参List类型字段中的某一个参数进行NULL校验,发现平台的内置函数不支持该场景的配置,这里就可以通过平台的机制,对内置函数进行扩展。 常见的一些代码场景,如下: package pro.shushi.pamirs.demo.core.action; ……引用类 @Model.model(PetShopProxy.MODEL_MODEL) @Component public class PetShopProxyAction extends DataStatusBehavior<PetShopProxy> { @Override protected PetShopProxy fetchData(PetShopProxy data) { return data.queryById(); } @Validation(ruleWithTips = { @Validation.Rule(value = "!IS_BLANK(data.code)", error = "编码为必填项"), @Validation.Rule(value = "LEN(data.name) < 128", error = "名称过长,不能超过128位"), }) @Action(displayName = "启用") @Action.Advanced(invisible="!(activeRecord.code !== undefined && !IS_BLANK(activeRecord.code))") public PetShopProxy dataStatusEnable(PetShopProxy data){ data = super.dataStatusEnable(data); data.updateById(); return data; } ……其他代码 } 2. 新建一个自定义表达式的函数 校验入参如果是个集合对象的情况下,单个对象的某个字段如果为空,返回false的函数。 例子:新建一个CustomCollectionFunctions类 package xxx.xxx.xxx; import org.apache.commons.collections4.CollectionUtils; import org.springframework.stereotype.Component; import pro.shushi.pamirs.meta.annotation.Fun; import pro.shushi.pamirs.meta.annotation.Function; import pro.shushi.pamirs.meta.common.constants.NamespaceConstants; import pro.shushi.pamirs.meta.util.FieldUtils; import java.util.List; import static pro.shushi.pamirs.meta.enmu.FunctionCategoryEnum.COLLECTION; import static pro.shushi.pamirs.meta.enmu.FunctionLanguageEnum.JAVA; import static pro.shushi.pamirs.meta.enmu.FunctionOpenEnum.LOCAL; import static pro.shushi.pamirs.meta.enmu.FunctionSceneEnum.EXPRESSION; /** * 自定义内置函数 */ @Fun(NamespaceConstants.expression) @Component public class CustomCollectionFunctions { /** * LIST_FIELD_NULL 就是我们自定义的表达式,不能与已经存在的表达式重复!!! * * @param list * @param field * @return */ @Function.Advanced( displayName = "校验集成的参数是否为null", language = JAVA, builtin = true, category = COLLECTION ) @Function.fun("LIST_FIELD_NULL") @Function(name = "LIST_FIELD_NULL", scene = {EXPRESSION}, openLevel = LOCAL, summary = "函数示例: LIST_FIELD_NULL(list,field),函数说明: 传入一个对象集合,校验集合的字段是否为空" ) public Boolean listFieldNull(List list, String field) { if (null == list) { return false; } if (CollectionUtils.isEmpty(list)) { return false; } for (Object data : list) { Object value =…

    2024年5月30日
    2.7K00
  • Oinone平台可视化调试工具

    为方便开发者定位问题,我们提供了可视化的调试工具。
    该文档将介绍可视化调试工具的基本使用方法。

    2024年4月13日
    1.5K00

Leave a Reply

登录后才能评论