Lzh on GitHub
<script setup lang="ts">
import {

  FlexRender,
  getCoreRowModel,
  useVueTable,

  createColumnHelper
} from '@tanstack/vue-table'
import type { ColumnOrderState, Column } from '@tanstack/vue-table'

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

const columnHelper = createColumnHelper<Person>()

const data = ref(makeData(20))

const columns = ref([
  columnHelper.group({
    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,值为是否可见
const columnVisibility = ref({})
// 用于存储表格列的排序状态,数组中列ID的顺序决定了列在表格中的显示顺序
const columnOrder = ref<ColumnOrderState>([])

const rerender = () => (data.value = makeData(20))

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

  // 如果提供了此函数,当 state.columnOrder 改变时,将使用 updaterFn 调用此函数。这会覆盖默认的内部状态管理,因此你需要完全或部分地在表格外部持久化状态更改。
  onColumnOrderChange: (order) => {
    columnOrder.value = order instanceof Function ? order(columnOrder.value) : order
  },
  // 这个必需选项是一个函数的工厂函数,该函数用于计算并返回表格的核心行模型。它会为每个表格调用一次,并且应该返回一个新函数,该新函数将计算并返回表格的行模型。
  getCoreRowModel: getCoreRowModel(),
  debugTable: true,
  debugHeaders: true,
  debugColumns: true
})

/**
 * 随机打乱表格列的显示顺序
 * 使用 faker 的 shuffle 方法将所有叶子列的 ID 顺序随机打乱
 */
const randomizeColumns = () => {
  table.setColumnOrder(
    // 获取所有叶子列(最底层的列,非分组列),提取它们的 ID,
    // 然后使用 faker.helpers.shuffle 随机打乱顺序,并设置为新的列顺序
    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 shadow rounded">
      <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="border p-1"
        @click="rerender"
      >
        Regenerate
      </button>
      <button
        class="border p-1"
        @click="randomizeColumns"
      >
        Shuffle Columns
      </button>
    </div>
    <div class="h-4" />

    <table>
      <thead>
        <tr
          v-for="headerGroup in table.getHeaderGroups()"
          :key="headerGroup.id"
        >
          <th
            v-for="header in headerGroup.headers"
            :key="header.id"
            :colSpan="header.colSpan"
          >
            <FlexRender
              v-if="!header.isPlaceholder"
              :render="header.column.columnDef.header"
              :props="header.getContext()"
            />
          </th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="row in table.getRowModel().rows"
          :key="row.id"
        >
          <td
            v-for="cell in row.getVisibleCells()"
            :key="cell.id"
          >
            <FlexRender
              :render="cell.column.columnDef.cell"
              :props="cell.getContext()"
            />
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr
          v-for="footerGroup in table.getFooterGroups()"
          :key="footerGroup.id"
        >
          <th
            v-for="header in footerGroup.headers"
            :key="header.id"
            :colSpan="header.colSpan"
          >
            <FlexRender
              v-if="!header.isPlaceholder"
              :render="header.column.columnDef.footer"
              :props="header.getContext()"
            />
          </th>
        </tr>
      </tfoot>
    </table>
    <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>