Lzh on GitHub
<script setup lang="ts">
import {
  createColumnHelper,
  FlexRender,
  getCoreRowModel,
  useVueTable
} from '@tanstack/vue-table'
import type {
  Column,
  ColumnOrderState,
  ColumnPinningState
} from '@tanstack/vue-table'

import { makeData } from './makeData'
import type { Person } from './makeData'
import { ref } from 'vue'
import { faker } from '@faker-js/faker'

const data = ref(makeData(100))

const columnHelper = createColumnHelper<Person>()

const columns = ref([
  columnHelper.group({
    // id: 'Name',
    header: 'Name',
    footer: props => props.column.id,
    columns: [
      columnHelper.accessor('firstName', {
        cell: info => info.getValue(),
        footer: props => props.column.id
      }),
      columnHelper.accessor(row => row.lastName, {
        id: 'lastName',
        cell: info => info.getValue(),
        header: () => 'Last Name',
        footer: props => props.column.id
      })
    ]
  }),
  columnHelper.group({
    header: 'Info',
    footer: props => props.column.id,
    columns: [
      columnHelper.accessor('age', {
        header: () => 'Age',
        footer: props => props.column.id
      }),
      columnHelper.group({
        header: 'More Info',
        columns: [
          columnHelper.accessor('visits', {
            header: () => 'Visits',
            footer: props => props.column.id
          }),
          columnHelper.accessor('status', {
            header: 'Status',
            footer: props => props.column.id
          }),
          columnHelper.accessor('progress', {
            header: 'Profile Progress',
            footer: props => props.column.id
          })
        ]
      })
    ]
  })
])

// 用于控制表格列的可见性状态,键为列ID,值为是否可见(true表示可见,false或undefined表示隐藏)
const columnVisibility = ref({})
// 用于存储表格列的排序状态,数组中列ID的顺序决定了列在表格中的显示顺序
const columnOrder = ref<ColumnOrderState>([])
// 用于控制表格列的固定状态,包含left和right两个数组,分别表示固定在左侧和右侧的列ID
const columnPinning = ref<ColumnPinningState>({})
// 控制是否启用分列显示模式的开关状态,true表示将固定列和普通列分开显示,false表示统一显示
const isSplit = ref(false)

// 重新生成表格数据的函数,使用100条新数据替换现有数据
const rerender = () => (data.value = makeData(100))

const table = useVueTable({
  get data() {
    return data.value
  },
  get columns() {
    return columns.value
  },
  state: {
    get columnVisibility() {
      return columnVisibility.value
    },
    get columnOrder() {
      return columnOrder.value
    },
    get columnPinning() {
      return columnPinning.value
    }
  },

  /**
   * 列顺序变化时的回调函数
   * 当用户通过拖拽或其他方式改变列的显示顺序时触发
   * @param order 新的列顺序状态,可以是直接的列ID数组或更新函数
   */
  onColumnOrderChange: (order) => {
    // 如果 order 是函数,则调用该函数传入当前列顺序值,否则直接使用 order 值
    columnOrder.value = order instanceof Function ? order(columnOrder.value) : order
  },
  /**
   * 列固定状态变化时的回调函数
   * 当用户固定或取消固定某列时触发
   * @param pinning 新的列固定状态,包含 left 和 right 两个数组
   */
  onColumnPinningChange: (pinning) => {
    // 如果 pinning 是函数,则调用该函数传入当前列固定状态值,否则直接使用 pinning 值
    columnPinning.value = pinning instanceof Function ? pinning(columnPinning.value) : pinning
  },
  getCoreRowModel: getCoreRowModel(),
  debugTable: true,
  debugHeaders: true,
  debugColumns: true
})

/**
 * 随机打乱表格列的显示顺序
 * 使用 faker 的 shuffle 方法将所有叶子列的 ID 顺序随机打乱
 */
const randomizeColumns = () => {
  // 获取所有叶子列(最底层的列,非分组列),提取它们的 ID,
  // 然后使用 faker.helpers.shuffle 随机打乱顺序,并设置为新的列顺序
  table.setColumnOrder(
    faker.helpers.shuffle(table.getAllLeafColumns().map(d => d.id))
  )
}

/**
 * 切换指定列的可见性状态
 * @param column 要切换可见性的列对象
 */
function toggleColumnVisibility(column: Column<any, any>) {
  // 使用展开运算符保留现有的可见性设置,
  // 并将当前列的可见性设为其当前状态的相反值
  columnVisibility.value = {
    ...columnVisibility.value,
    [column.id]: !column.getIsVisible() // 切换当前列的可见性
  }
}

/**
 * 切换所有列的可见性状态
 * 遍历所有叶子列并逐个切换它们的可见性
 */
function toggleAllColumnsVisibility() {
  // 获取所有叶子列并逐个调用 toggleColumnVisibility 函数
  table.getAllLeafColumns().forEach((column) => {
    toggleColumnVisibility(column)
  })
}
</script>

<template>
  <div class="p-2">
    <div class="inline-block border border-black rounded shadow">
      <div class="px-1 border-b border-black">
        <label>
          <input
            type="checkbox"
            :checked="table.getIsAllColumnsVisible()"
            @input="toggleAllColumnsVisibility"
          >
          Toggle All
        </label>
      </div>
      <div
        v-for="column in table.getAllLeafColumns()"
        :key="column.id"
        class="px-1"
      >
        <label>
          <input
            type="checkbox"
            :checked="column.getIsVisible()"
            @input="toggleColumnVisibility(column)"
          >
          {{ column.id }}
        </label>
      </div>
    </div>
    <div class="h-4" />
    <div class="flex flex-wrap gap-2">
      <button
        class="p-1 border"
        @click="rerender"
      >
        Regenerate
      </button>
      <button
        class="p-1 border"
        @click="randomizeColumns"
      >
        Shuffle Columns
      </button>
    </div>
    <div class="h-4" />
    <div>
      <label>
        <input
          v-model="isSplit"
          type="checkbox"
        >
        Split Mode
      </label>
    </div>
    <div class="h-4" />
    <div :class="`flex ${isSplit ? 'gap-4' : ''}`">
      <!-- left -->
      <table
        v-if="isSplit"
        class="border-2 border-black table-left"
      >
        <thead>
          <tr
            v-for="headerGroup in table.getLeftHeaderGroups()"
            :key="headerGroup.id"
          >
            <th
              v-for="header in headerGroup.headers"
              :key="header.id"
              :colSpan="header.colSpan"
            >
              <div class="whitespace-nowrap">
                <FlexRender
                  v-if="!header.isPlaceholder"
                  :render="header.column.columnDef.header"
                  :props="header.getContext()"
                />
              </div>
              <div
                v-if="!header.isPlaceholder && header.column.getCanPin()"
                class="flex justify-center gap-1"
              >
                <button
                  v-if="header.column.getIsPinned() !== 'left'"
                  class="px-2 border rounded"
                  @click="header.column.pin('left')"
                >
                  {{ '<=' }}
                </button>
                <button
                  v-if="header.column.getIsPinned()"
                  class="px-2 border rounded"
                  @click="header.column.pin(false)"
                >
                  X
                </button>
                <button
                  v-if="header.column.getIsPinned() !== 'right'"
                  class="px-2 border rounded"
                  @click="header.column.pin('right')"
                >
                  {{ '=>' }}
                </button>
              </div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="row in table.getRowModel().rows.slice(0, 20)"
            :key="row.id"
          >
            <td
              v-for="cell in row.getLeftVisibleCells()"
              :key="cell.id"
            >
              <FlexRender
                :render="cell.column.columnDef.cell"
                :props="cell.getContext()"
              />
            </td>
          </tr>
        </tbody>
      </table>
      <!-- center -->
      <table class="border-2 border-black table-center">
        <thead>
          <tr
            v-for="headerGroup in isSplit
              ? table.getCenterHeaderGroups()
              : table.getHeaderGroups()"
            :key="headerGroup.id"
          >
            <th
              v-for="header in headerGroup.headers"
              :key="header.id"
              :colSpan="header.colSpan"
            >
              <div class="whitespace-nowrap">
                <FlexRender
                  v-if="!header.isPlaceholder"
                  :render="header.column.columnDef.header"
                  :props="header.getContext()"
                />
              </div>
              <div
                v-if="!header.isPlaceholder && header.column.getCanPin()"
                class="flex justify-center gap-1"
              >
                <button
                  v-if="header.column.getIsPinned() !== 'left'"
                  class="px-2 border rounded"
                  @click="header.column.pin('left')"
                >
                  {{ '<=' }}
                </button>
                <button
                  v-if="header.column.getIsPinned()"
                  class="px-2 border rounded"
                  @click="header.column.pin(false)"
                >
                  X
                </button>
                <button
                  v-if="header.column.getIsPinned() !== 'right'"
                  class="px-2 border rounded"
                  @click="header.column.pin('right')"
                >
                  {{ '=>' }}
                </button>
              </div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="row in table.getRowModel().rows.slice(0, 20)"
            :key="row.id"
          >
            <td
              v-for="cell in isSplit
                ? row.getCenterVisibleCells()
                : row.getVisibleCells()"
              :key="cell.id"
            >
              <FlexRender
                :render="cell.column.columnDef.cell"
                :props="cell.getContext()"
              />
            </td>
          </tr>
        </tbody>
      </table>
      <!-- right -->
      <table
        v-if="isSplit"
        class="border-2 border-black table-right"
      >
        <thead>
          <tr
            v-for="headerGroup in table.getRightHeaderGroups()"
            :key="headerGroup.id"
          >
            <th
              v-for="header in headerGroup.headers"
              :key="header.id"
              :colSpan="header.colSpan"
            >
              <div class="whitespace-nowrap">
                <FlexRender
                  v-if="!header.isPlaceholder"
                  :render="header.column.columnDef.header"
                  :props="header.getContext()"
                />
              </div>
              <div
                v-if="!header.isPlaceholder && header.column.getCanPin()"
                class="flex justify-center gap-1"
              >
                <button
                  v-if="header.column.getIsPinned() !== 'left'"
                  class="px-2 border rounded"
                  @click="header.column.pin('left')"
                >
                  {{ '<=' }}
                </button>
                <button
                  v-if="header.column.getIsPinned()"
                  class="px-2 border rounded"
                  @click="header.column.pin(false)"
                >
                  X
                </button>
                <button
                  v-if="header.column.getIsPinned() !== 'right'"
                  class="px-2 border rounded"
                  @click="header.column.pin('right')"
                >
                  {{ '=>' }}
                </button>
              </div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="row in table.getRowModel().rows.slice(0, 20)"
            :key="row.id"
          >
            <td
              v-for="cell in row.getRightVisibleCells()"
              :key="cell.id"
            >
              <FlexRender
                :render="cell.column.columnDef.cell"
                :props="cell.getContext()"
              />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <pre>{{ JSON.stringify(table.getState().columnOrder, null, 2) }}</pre>
  </div>
</template>

<style>
html,
body {
  padding: 4px;
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

table {
  border: 1px solid lightgray;
  border-collapse: collapse;
}

tbody {
  border-bottom: 1px solid lightgray;
}

th,
td {
  border-bottom: 1px solid lightgray;
  border-right: 1px solid lightgray;
  padding: 2px 4px;
}

th {
  padding: 8px;
}

tfoot {
  color: gray;
}

tfoot th {
  font-weight: normal;
}
</style>
左右箭头表示列是固定在左侧还是右侧。重新排序列时,固定列不会动。