Skip to content

列拖拽排序 ​

装 vtColumnDrag() 后拖拽表头即可调整列顺序,通过 onColumnOrderChange 拿到新顺序。与列宽拖拽、点击排序互不冲突(按拖拽阈值区分手势)。

示例 ​

微应用尚未挂载。

源码 ​

点击查看源码
ts
import { faker } from '@faker-js/faker';
import {
  VirtTable,
  type VirtTableColumn,
} from '@virt-table/vanilla';
import {
  vtColumnDrag,
} from '@virt-table/vanilla/plugins';

interface Row { id: number; name: string; age: number; city: string; job: string }

export function bootstrapTableColumnDrag(root: HTMLElement): () => void {
  const columns: VirtTableColumn<Row>[] = [
    { key: 'id', title: 'ID', width: 80, fixed: 'left' },
    { key: 'name', title: '姓名', width: 180 },
    { key: 'age', title: '年龄', width: 120 },
    { key: 'city', title: '城市', width: 180 },
    { key: 'job', title: '职位', width: 200 },
  ];

  const list: Row[] = Array.from({ length: 500 }, (_, i) => ({
    id: i + 1,
    name: faker.person.fullName(),
    age: faker.number.int({ min: 18, max: 60 }),
    city: faker.location.city(),
    job: faker.person.jobTitle(),
  }));

  root.innerHTML = `
    <div class="demo-hint">拖拽<b>表头</b>调整列顺序(固定列 ID 不建议拖动)。顺序变化见控制台。</div>
    <div style="width:760px;height:480px;" class="demo-container" id="c"></div>`;
  const container = root.querySelector('#c') as HTMLElement;

  const table = new VirtTable<Row>(container, {
    plugins: [vtColumnDrag()],
    list,
    columns,
    itemKey: 'id',
    estimatedSize: 40,
    buffer: 6,
    border: true,
    onColumnOrderChange: (cols) => console.log('列顺序:', cols.map((c) => c.key)),
  });

  return () => {
    table.destroy();
    root.innerHTML = '';
  };
}

说明 ​

ts
import { vtColumnDrag } from '@virt-table/vanilla/plugins';
import '@virt-table/vanilla/plugins/drag-sort.css';

new VirtTable(el, { list, columns, itemKey: 'id', estimatedSize: 40,
  plugins: [vtColumnDrag()],
  onColumnOrderChange: (columns) => save(columns.map((c) => c.key)),
});

相关 API ​

字段 / 方法作用详见
vtColumnDrag()拖拽表头调整列顺序插件机制
onColumnOrderChange列顺序变化回调列配置 · 拖拽排序
moveColumn(colKey, toIndex)编程式移动实例方法
getState() / setState()把列序存下来状态持久化

分组表头下只允许同一父分组内换位,跨分组拖拽被忽略;有 merges 时整体禁用。