Files
wukuang/user-scripts.md
T
2026-05-23 14:05:22 +08:00

3.3 KiB
Raw Blame History

User Scripts 事件开发指南

本文档记录如何为表单设计器添加新的组件事件。

添加 Table Cell 事件的完整步骤

以添加 cellFocuscellBlur 事件为例:

第一步:在 Events.ts 中添加枚举值

文件路径: packages/types/form-designer/user-script/Events.ts

CompEventEnum 枚举中添加新的事件类型:

export enum CompEventEnum {
  // ... 现有事件 ...
  TABLE_CELL_CONTEXT_MENU = "cellContextMenu",
  TABLE_CELL_FOCUS = "cellFocus", // 新增
  TABLE_CELL_BLUR = "cellBlur", // 新增
  TABLE_CELL_ALL_MOUNTED = "cellAllMounted",
  // ...
}

第二步:在 Table.ts 中添加事件配置

文件路径: packages/form-designer/src/config/user-script/eventInfo/comp/Table.ts

getTableCompEvents 数组中添加事件配置:

const getTableCompEvents: () => EventItemBO[] = () => [
  // ... 现有事件配置 ...
  {
    name: CompEventEnum.TABLE_CELL_FOCUS,
    label: t("userScript.events.component.tableCellFocus.label"),
    desc: t("userScript.events.component.tableCellFocus.desc"),
  },
  {
    name: CompEventEnum.TABLE_CELL_BLUR,
    label: t("userScript.events.component.tableCellBlur.label"),
    desc: t("userScript.events.component.tableCellBlur.desc"),
  },
  // ...
];

第三步:在 UseComp.ts 中添加触发函数

文件路径: packages/form-designer/src/config/user-script/hooks/UseComp.ts

  1. useCompEvent 函数内部添加处理函数:
function handleTableCellFocus(...args: any[]) {
  emitCompEvent(CompEventEnum.TABLE_CELL_FOCUS, args);
}
function handleTableCellBlur(...args: any[]) {
  emitCompEvent(CompEventEnum.TABLE_CELL_BLUR, args);
}
  1. 在 return 语句中导出函数:
return {
  // ... 现有导出 ...
  handleTableCellMouseEnter,
  handleTableCellMouseLeave,
  handleTableCellFocus, // 新增
  handleTableCellBlur, // 新增
  handleTableCellChagne,
  // ...
};

第四步:添加多语言配置

文件路径: packages/form-designer/src/locales/model/UserScript.json

userScript.events.component 节点下添加:

{
  "userScript": {
    "events": {
      "component": {
        // ... 现有配置 ...
        "tableCellFocus": {
          "label": "单元格聚焦",
          "desc": "表格单元格获得焦点时触发"
        },
        "tableCellBlur": {
          "label": "单元格失焦",
          "desc": "表格单元格失去焦点时触发"
        }
      }
    }
  }
}

通用步骤总结

为任何组件添加新事件的通用流程:

  1. 定义事件类型packages/types/form-designer/user-script/Events.ts 中的 CompEventEnum
  2. 配置事件信息packages/form-designer/src/config/user-script/eventInfo/comp/ 下的对应组件文件
  3. 实现触发函数packages/form-designer/src/config/user-script/hooks/UseComp.ts
  4. 添加多语言packages/form-designer/src/locales/model/UserScript.json

注意事项

  • 事件名称使用驼峰命名法(如 cellFocus
  • 枚举值使用大写下划线命名法(如 TABLE_CELL_FOCUS
  • 多语言 key 采用小驼峰命名(如 tableCellFocus
  • 如果事件是钩子函数(需要拦截/校验),需要设置 isHook: true
  • 如果事件仅供内部使用,设置 internal: true