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

Vaadin 21中找不到GridRowDragger类,是否有对应替代方案?

Vaadin 21 Grid行拖拽重排序实现方案

com.vaadin.ui.components.grid.GridRowDragger<T> 是Vaadin 8版本的专属组件,Vaadin 10及之后的版本(包括你使用的Vaadin 21)对Grid的拖拽API做了全量重构,官方已经移除了该类,直接通过Grid内置的拖拽、放置相关原生API即可实现行拖拽重排序功能,无需引入额外的第三方组件。


实现步骤

1. 开启Grid拖拽和放置能力

相关API都在com.vaadin.flow.component.grid.dnd包下,直接导入使用即可:

import com.vaadin.flow.component.grid.dnd.GridDropMode;
import com.vaadin.flow.component.grid.dnd.DropLocation;

// 初始化Grid,YourBean替换为你的表格绑定实体类
Grid<YourBean> grid = new Grid<>(YourBean.class);
// 开启行拖拽功能
grid.setRowsDraggable(true);
// 设置放置模式为行之间,适配重排序场景
grid.setDropMode(GridDropMode.BETWEEN);

2. 监听放置事件实现重排序逻辑

grid.addDropListener(event -> {
    // 获取被拖拽的所有行数据
    List<YourBean> draggedItems = event.getDraggedItems();
    // 获取放置位置的目标行数据
    Optional<YourBean> targetItemOpt = event.getDropTargetItem();
    if (draggedItems.isEmpty() || targetItemOpt.isEmpty()) {
        return;
    }
    YourBean targetItem = targetItemOpt.get();
    DropLocation dropLocation = event.getDropLocation();

    // 从当前内存数据源中移除被拖拽的元素
    List<YourBean> dataSource = grid.getListDataView().getItems().collect(Collectors.toList());
    dataSource.removeAll(draggedItems);

    // 计算插入位置:BEFORE为目标行上方,AFTER为目标行下方
    int insertIndex = dataSource.indexOf(targetItem);
    if (dropLocation == DropLocation.AFTER) {
        insertIndex++;
    }

    // 插入被拖拽的元素并刷新Grid
    dataSource.addAll(insertIndex, draggedItems);
    grid.setItems(dataSource);
});

3. 可选扩展配置

  • 可通过addDragStartListener自定义拖拽触发规则,比如禁止特定状态的行被拖拽
  • 可通过setDropAllowed方法自定义允许放置的区域,避免非法排序
  • TreeGrid的拖拽重排序逻辑和普通Grid完全一致,仅需额外处理数据层级字段的赋值即可
  • 若使用的是后端分页数据源,重排序逻辑完成后需调用后端接口更新数据的排序字段值,再重新拉取数据刷新Grid即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:06:00