如何为 Grid 添加滑动删除功能?

解读

国内面试官问“滑动删除”并不是想听“Vaadin 官方没这组件,做不了”。
他真正考察的是:

  1. 你是否理解 Vaadin 的“服务器端事件模型”与“客户端渲染层”之间的分工;
  2. 能否把移动端常见的“左滑出现删除按钮”交互,用 Vaadin 的 WebComponent 扩展机制落地;
  3. 是否具备“最小侵入、可复用、可维护”的企业级编码习惯(Spring 托管、样式隔离、i18n、安全、事务、并发、审计)。
    因此,回答必须给出“从前端手势到后端事务”的完整闭环,并说明性能、可访问性、兼容性、异常处理、回滚策略。

知识点

  1. 客户端层:

    • Vaadin 使用 Lit 框架渲染 <vaadin-grid>,其内部用 vaadin-grid-column-renderer-mixin 暴露 cellPart 插槽;
    • 通过 grid.addEventListener('touchstart') / 'touchmove' / 'touchend' 计算 deltaX,当 deltaX < -60px 时给当前行加 .swipe-open 类;
    • 用 CSS transform: translateX(-60px) 把行左移,露出右侧“删除”按钮;
    • 按钮用 <vaadin-button theme="error"> 实现,点击后通过 @ClientCallable 把行主键回传服务器。
  2. 服务器层:

    • 自定义 SwipeGrid<T> 继承 Grid<T>,在 setItems() 时给每一行生成唯一 rowId;
    • 用 Element.setProperty('rowId', id) 把主键写进 DOM,供客户端回调时带回;
    • 暴露 @ClientCallable(deleteRow) 方法,方法内用 Spring 事务模板删除数据库记录,删除成功后调用 getDataProvider().refreshAll();
    • 若删除失败抛 CustomException,通过 VaadinSession.errorHandler 统一弹 Notification,并自动回滚事务。
  3. 企业约束:

    • 权限:方法上加 @Secured('ROLE_ADMIN'),配合 Spring Security 上下文;
    • 审计:用 @EntityListeners(AuditingEntityListener.class) 记录操作人、时间;
    • 并发:数据库行加乐观锁 @Version,版本冲突时返回“数据已被他人修改”提示;
    • 性能:数据量 >1k 行时,用 DataProvider.fromCallbacks() 做懒加载,避免 refreshAll() 全表刷;
    • 可访问性:同时支持键盘 Delete 键与屏幕阅读器 aria-label="删除";
    • 移动端兼容:在 touchstart 里加 e.preventDefault() 防止页面整体左右滑动。

答案

  1. 新建 frontend/swipe-grid-column.js
import {html} from 'lit';
export class SwipeGridColumn extends HTMLElement {
  static get is() { return 'swipe-grid-column'; }
  constructor() {
    super();
    this.attachShadow({mode: 'open'});
    this.startX = 0;
    this.currentRow = null;
  }
  connectedCallback() {
    const grid = this.closest('vaadin-grid');
    grid.addEventListener('touchstart', e => this.handleStart(e), {passive: false});
    grid.addEventListener('touchmove',  e => this.handleMove(e),  {passive: false});
    grid.addEventListener('touchend',   e => this.handleEnd(e));
  }
  handleStart(e) {
    this.startX = e.touches[0].pageX;
    this.currentRow = e.target.closest('tr');
  }
  handleMove(e) {
    const dx = e.touches[0].pageX - this.startX;
    if (dx < -60) {
      this.currentRow.classList.add('swipe-open');
      this.currentRow.style.transform = `translateX(${dx}px)`;
    }
  }
  handleEnd(e) {
    const dx = e.changedTouches[0].pageX - this.startX;
    if (dx > -60) {
      this.currentRow.classList.remove('swipe-open');
      this.currentRow.style.transform = '';
    }
  }
}
customElements.define(SwipeGridColumn.is, SwipeGridColumn);
  1. 新建 SwipeGrid.java
@Tag("swipe-grid-column")
@JsModule("./swipe-grid-column.js")
public class SwipeGrid<T> extends Grid<T> {
    private final CrudService<T, ID> service;
    public SwipeGrid(CrudService<T, ID> service, Class<T> beanType) {
        super(beanType);
        this.service = service;
        addColumn(new ComponentRenderer<>(item -> {
            Button del = new Button("删除", VaadinIcon.TRASH.create());
            del.addThemeVariants(ButtonVariant.LUMO_ERROR);
            del.addClickListener(e -> deleteRow(item));
            del.getElement().setAttribute("slot", "delete-button");
            return del;
        })).setKey("delete").setWidth("60px").setFlexGrow(0);
    }
    @ClientCallable
    @Secured("ROLE_ADMIN")
    private void deleteRow(JsonObject rowData) {
        ID id = extractId(rowData);
        try {
            service.delete(id);
            getDataProvider().refreshAll();
            Notification.show("删除成功", 3000, Position.TOP_END);
        } catch (Exception ex) {
            Notification.show("删除失败:" + ex.getMessage(), 5000, Position.TOP_END);
            throw new CustomException("删除失败", ex);
        }
    }
}
  1. 使用
SwipeGrid<User> grid = new SwipeGrid<>(userService, User.class);
grid.setColumns("username", "email", "createTime");
grid.setItems(DataProvider.fromCallbacks(
        q -> userService.findAll(PageRequest.of(q.getPage(), q.getPageSize())).stream(),
        q -> (int) userService.count()
));
add(grid);
  1. 样式隔离
    在 styles/grid-swipe.css 中写
.swipe-open { transition: transform .2s; }

并在 @Theme 注解里 addCssImport("grid-swipe.css")。

拓展思考

  1. 如果列表需要“批量滑动+批量删除”,可以把 SwipeGrid 改成多选模式,滑动后把行加入 Set<T>,顶部出现 Toolbar 统一提交,减少事务次数。
  2. 在 PC 端可监听 mousemove 实现“横向拖拽”出现删除按钮,做到同一套代码多端适配。
  3. 对于敏感数据,可在滑动后先弹出 ConfirmDialog,要求二次输入用户名或验证码,防止误触。
  4. 若数据量极大,可改用 vaadin-virtual-list 并自定义 renderer,滑动删除逻辑相同,但内存占用更低。
  5. 从 UX 角度,可加入“撤销”浮层:删除后前端先本地移除,5 秒内可点击“撤销”,服务器端用延迟队列真正物理删除,提升用户体验。