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

在 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

相关推荐

  • OioMessage 全局提示

    全局展示操作反馈信息。 何时使用 可提供成功、警告和错误等反馈信息。 顶部居中显示并自动消失,是一种不打断用户操作的轻量级提示方式。 API 组件提供了一些静态方法,使用方式和参数如下: OioMessage.success(title, options) OioMessage.error(title, options) OioMessage.info(title, options) OioMessage.warning(title, options) options 参数如下: 参数 说明 类型 默认值 版本 duration 默认 3 秒后自动关闭 number 3 class 自定义 CSS class string –

    2023年12月18日
    1.2K00
  • 如何在表格的字段内添加动作

    介绍 在日常的业务中,我们经常需要在表格内直接点击动作完成一些操作,而不是只能在操作栏中,例如:订单的表格内点击商品名称或者里面的按钮跳转到商品详情页面,这里我们将带来大家来通过自定义表格字段来实现这个功能。 1.编写表格字段组件 组件ts文件TableBtnFieldWidget.ts import { ActionWidget, ActiveRecordExtendKeys, BaseFieldWidget, BaseListView, ModelFieldType, queryDslWidget, queryRowActionBar, RowContext, SPI, TableStringFieldWidget, BaseElementListViewWidget, ViewType, Widget } from '@kunlun/dependencies'; import { createVNode, VNode } from 'vue'; import { toString } from 'lodash-es'; import TableBtnField from './TableBtnField.vue'; @SPI.ClassFactory( BaseFieldWidget.Token({ viewType: ViewType.Table, ttype: [ModelFieldType.String, ModelFieldType.Text], // widget: 'StringLink', // 以下3行配置代码测试用,生产建议在界面设计器自定义组件,widget填自定义组件的api名称 model: 'resource.k2.Model0000000109', name: 'name' }) ) export class TableBtnFieldWidget extends TableStringFieldWidget { @Widget.Reactive() private get triggerActionLabel() { // 界面设计器组件内设计该属性 return this.getDsl().triggerActionLabel || '更新'; } private getTriggerAction() { return this.model.modelActions.find((a) => a.label === this.triggerActionLabel); } private getTriggerActionWidget(widgetHandle: string, draftId: string, triggerActionLabel: string): ActionWidget | undefined { const listView = Widget.select(widgetHandle) as unknown as BaseListView; const listWidget = queryDslWidget(listView?.getChildrenInstance(), BaseElementListViewWidget); if (!listWidget) { return undefined; } const rowActionBar = queryRowActionBar(listWidget.getChildrenInstance(), draftId); const actionWidget = rowActionBar?.getChildrenInstance().find((a) => (a as ActionWidget).action.label === triggerActionLabel); return actionWidget as ActionWidget; } protected clickAction(context: RowContext) { const draftId = context.data[ActiveRecordExtendKeys.DRAFT_ID] as unknown as string; const actionWidget = this.getTriggerActionWidget(this.getRootHandle()!, draftId, this.triggerActionLabel); if (!actionWidget) { console.error('未找到action', this.triggerActionLabel); return; } actionWidget.click(); } @Widget.Method() public renderDefaultSlot(context: RowContext): VNode[] | string { const value = toString(this.compute(context)); if (value) { return [ createVNode(TableBtnField,…

    2024年5月16日
    1.5K00
  • 前端-如何修改指定页面的内组件的css样式

    为组件加自定义class,用该class作为父选择器写特定的css样式 以form为例,自定义了以下class <view/>标签的表单视图(FormView)组件 <element/>标签的form(FormWidget)组件 <element/>标签的actionBar(ActionBarWidget)组件 import { registerLayout, ViewType } from '@kunlun/dependencies'; export const install = () => { registerLayout( ` <view type="FORM" class="my-form-view"> <element widget="form" slot="form" class="my-form-widget"> <xslot name="fields" slotSupport="pack,field" /> </element> <element widget="actionBar" slot="actionBar" class="my-action-bar" slotSupport="action" > <xslot name="actions" slotSupport="action" /> </element> </view> `, { viewType: ViewType.Form, model: 'resource.k2.Model0000000109', actionName: 'uiViewb2de116be1754ff781e1ffa8065477fa' } ); }; install(); 查看修改后的页面html结构 编写样式的css .my-form-view .oio-form { /** TODO **/ } .my-form-widget .oio-row { /** TODO **/ } .my-action-bar .oio-col { /** TODO **/ }

    2024年6月17日
    1.4K00
  • oio-modal 对话框

    API 参数 说明 类型 默认值 版本 cancelText 取消按钮文字 string| slot 取消 closable 是否显示右上角的关闭按钮 boolean true closeIcon 自定义关闭图标 VNode | slot – confirmLoading 确定按钮 loading boolean 无 destroyOnClose 关闭时销毁 Modal 里的子元素 boolean false footer 底部内容,当不需要默认底部按钮时,可以设为 :footerInvisible="true" slot 确定取消按钮 getTriggerContainer 指定 Modal 挂载的 HTML 节点 (instance): HTMLElement () => document.body keyboard 是否支持键盘 esc 关闭 boolean true mask 是否展示遮罩 boolean true maskClosable 点击蒙层是否允许关闭 boolean true enterText 确认按钮文字 string 确定 title 标题 string|slot 无 visible(v-model:visible) 对话框是否可见 boolean 无 width 宽度 string|number 520 wrapClassName 对话框外层容器的类名 string – zIndex 设置 Modal 的 z-index number 1000 cancelCallback 点击遮罩层或右上角叉或取消按钮的回调, return true则关闭弹窗 function(e) enterCallback 点击确定回调 function(e)

    2023年12月18日
    1.6K00
  • 如何自定义 GraphQL 请求

    在开发过程中,有时需要自定义 GraphQL 请求来实现更灵活的数据查询和操作。本文将介绍两种主要的自定义 GraphQL 请求方式:手写 GraphQL 请求和调用平台 API。 方式一:手写 GraphQL 请求 手写 GraphQL 请求是一种直接编写查询或变更语句的方式,适用于更复杂或特定的业务需求。以下分别是 query 和 mutation 请求的示例。 1. 手写 Query 请求 以下是一个自定义 query 请求的示例,用于查询某个资源的语言信息列表。 const customQuery = async () => { const query = `{ resourceLangQuery { queryListByEntity(query: {active: ACTIVE, installState: true}) { id name active installState code isoCode } } }`; const result = await http.query('resource', query); this.list = result.data['resourceLangQuery']['queryListByEntity']; }; 说明: query 语句定义了一个请求,查询 resourceLangQuery 下的语言信息。 查询的条件是 active 和 installState,只返回符合条件的结果。 查询结果包括 id、name、active、installState 等字段。 2. 手写 Mutation 请求 以下是一个 mutation 请求的示例,用于创建新的资源分类信息。 const customMutation = async () => { const code = Date.now() const name = `测试${code}` const mutation = `mutation { resourceTaxKindMutation { create(data: {code: "${code}", name: "${name}"}) { id code name createDate writeDate createUid writeUid } } }`; const res = await http.mutate('resource', mutation); console.log(res); }; 说明: mutation 语句用于创建一个新的资源分类。 create 操作的参数是一个对象,包含 code 和 name 字段。 返回值包括 id、createDate 等字段。 方式二:调用平台的 API 平台 API 提供了简化的 GraphQL 调用方法,可以通过封装的函数来发送 query 和 mutation 请求。这种方式减少了手写 GraphQL 语句的复杂性,更加简洁和易于维护。 1. 调用平台的 Mutation API 使用平台的 customMutation 方法可以简化 Mutation 请求。 /** * 自定义请求方法 * @param modelModel 模型编码 * @param method 方法名或方法对象 * @param records 请求参数,可以是单体对象或者对象的列表 * @param requestFields…

    2024年9月21日
    1.8K00

Leave a Reply

登录后才能评论