You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Formio.js中Select组件变更前后的值(含DataGrid场景)

解决Formio.js DataGrid中Select组件获取变更前后值的问题

核心思路

借助Formio的组件生命周期事件,结合动态组件的唯一标识,精准捕获每个下拉框(包括DataGrid新增行生成的下拉框)的变更前、后值。

实现方案

方案一:利用表单全局事件监听

// 初始化表单实例
const form = new Formio(document.getElementById('formio'));
// 用Map存储每个下拉框的旧值,以组件唯一instanceId为键
const oldValueMap = new Map();

form.ready.then(() => {
  // 监听值变更前事件,记录旧值
  form.on('beforeChange', (component, newValue, oldValue) => {
    if (component.key === 'testDropDown') {
      oldValueMap.set(component.instanceId, oldValue);
    }
  });

  // 监听值变更完成事件,获取当前值与旧值
  form.on('change', (component, newValue) => {
    if (component.key === 'testDropDown') {
      const prevValue = oldValueMap.get(component.instanceId);
      console.log(`当前值: ${newValue}, 变更前值: ${prevValue}`);
      // 此处添加你的业务逻辑
    }
  });
});

方案二:给Select组件添加自定义变更事件

直接修改表单配置中的Select组件,添加自定义变更处理函数:

// 修改后的Select组件配置片段
{
  label     : 'Test drop down',
  widget    : 'choicesjs',
  tableView : true,
  data: {
    values: [
      { label: 'Test 1', value: 'test1' },
      { label: 'Test 2', value: 'test2' },
      { label: 'Test 3', value: 'test3' }
    ]
  },
  key       : 'testDropDown',
  type      : 'select',
  input     : true,
  // 自定义变更事件,自动传入当前值与旧值
  customOnChange: function(currentValue, previousValue) {
    console.log(`当前值: ${currentValue}, 变更前值: ${previousValue}`);
    // 业务逻辑写在这里
  }
}

关键说明

  • DataGrid动态生成的每个组件都有唯一instanceId,用Map存储旧值可精准匹配对应下拉框。
  • 方案一通过全局事件监听适配所有动态生成的组件,方案二直接在组件配置中定义逻辑,更轻量化。

内容的提问来源于stack exchange,提问作者Philiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:53:20