# Table

> 用真实表格语义呈现结构化数据，复用现有控件、分页与状态反馈。

网页来源：/components/table

版本：@quirekit/ui 0.3.1；源码修订：d79a6b48d00e+worktree。此文档对应当前源码构建，接入方式以开始使用为准。

接入前置：[开始使用](/raw/components/getting-started.md)（Vue、样式、主题与图标 Provider）。

## 基本用法

`rows` 提供记录，`columns` 定义列，`rowKey` 指定稳定且唯一的业务标识。`label` 或 `caption` 为表格命名；Table 展示传入的全部行，分页由页面处理。

### 示例：table/simple

文件：`simple.vue`

```vue
<script setup lang="ts">
import { QuireTable } from '@quirekit/ui/vue';
const rows = [
  { id: 'plan', name: '季度产品计划', owner: '林舒' },
  { id: 'review', name: '项目复盘记录', owner: '陈清' },
];
const columns = [
  { id: 'name', field: 'name' as const, title: '文档', rowHeader: true },
  { id: 'owner', field: 'owner' as const, title: '负责人' },
];
</script>
<template>
  <div class="min-w-0 p-qk-surface"><QuireTable :rows="rows" :columns="columns" row-key="id" label="项目文档" /></div>
</template>
```

列的 `field` 读取属性，`value(row)` 计算显示内容；`width` 设置列宽，`align` 设置对齐方式，`rowHeader` 将该列作为行标题。

## 排序与选择

列设置 `sortable: true` 开启排序，点击依次切换升序、降序和未排序。`selectable` 开启多选，通过 `v-model:selected-keys` 保存选择，`rowSelectable` 排除不可选记录。
表头全选只作用于当前页可选行，翻页后保留选择。

### 示例：table/sorting-selection

文件：`sorting-selection.vue`

```vue
<script setup lang="ts">
import { computed, ref } from 'vue';
import type { QuireKitTableSorting, QuireKitTableColumn } from '@quirekit/ui';
import { QuireTable, QuireButton, QuirePagination, sortTableRows } from '@quirekit/ui/vue';
/** Full dataset owned by the local host, or by the simulated service. */
const tableDocuments = Array.from({ length: 18 }, (_, index) => ({
  id: `record-${index + 1}`, name: `设计记录 ${String(index + 1).padStart(2, '0')}`,
  bytes: ((index * 7) % 18 + 1) * 120, archived: index === 2
}));
/** Comparators declare actual numeric and language ordering, not display-string guesses. */
const interactionColumns: QuireKitTableColumn<(typeof tableDocuments)[number]>[] = [
  { id: 'name', title: '文档', field: 'name', rowHeader: true, compare: (a, b) => a.name.localeCompare(b.name, 'zh-CN') },
  { id: 'size', title: '大小', value: row => `${row.bytes} KB`, compare: (a, b) => a.bytes - b.bytes },
  { id: 'status', title: '状态', value: row => row.archived ? '已归档' : '可编辑' }
];

const sorting = ref<QuireKitTableSorting | null>(null);
const selected = ref<string[]>([]);
const page = ref(1);
// Full filtered data is sorted before slicing; the table receives one manual page.
const ordered = computed(() => sortTableRows(tableDocuments, interactionColumns, sorting.value));
const rows = computed(() => ordered.value.slice((page.value - 1) * 5, page.value * 5));
/**
 * Restart paging when ordering changes, while keeping selected business keys.
 * @param value - Requested single-column state.
 */
function changeSorting(value: QuireKitTableSorting | null): void {
  sorting.value = value;
  page.value = 1;
}
</script>
<template>
  <div class="grid min-w-0 gap-qk-group p-qk-surface" data-table-interaction>
    <div class="flex flex-wrap items-center gap-qk-surface">
      <span role="status">已选 {{ selected.length }} 项</span>
      <QuireButton :disabled="!selected.length" @click="selected = []">清空选择</QuireButton>
      <span class="text-qk-text-secondary">已归档记录不可选；翻页保留选择。</span>
    </div>
    <QuireTable v-model:selected-keys="selected" :sorting="sorting" :rows="rows" :columns="interactionColumns" row-key="id" :row-label="row => row.name" :row-selectable="row => !row.archived" label="可排序文档" selectable min-width="32rem" @update:sorting="changeSorting">
      <template #footer><QuirePagination v-model:page="page" :count="tableDocuments.length" :page-size="5" :layout="['summary', 'spacer', 'previous', 'pages', 'next']" label="选择示例分页" /></template>
    </QuireTable>
  </div>
</template>
```

| 数据来源 | 排序方式 |
| --- | --- |
| 完整数据，不分页 | `sortingMode="local"`，列提供 `compare` 比较器 |
| 完整数据，在页面分页 | 先用 `sortTableRows` 排序，再切片，Table 保持默认 `manual` |
| 服务端分页 | 监听 `update:sorting`，请求服务端返回排序后的当前页 |

比较器使用原始值，例如 `compare: (a, b) => a.bytes - b.bytes`。删除记录或切换业务范围时，页面按需清理已选 key。

## 远程数据

请求期间设置 `loading`，表格保留旧行并暂停默认排序和选择操作。下例使用本地延迟模拟服务端分页，只接受最后一次请求的结果；接入接口时补充错误提示与重试。

### 示例：table/remote-sorting

文件：`remote-sorting.vue`

```vue
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue';
import type { QuireKitTableSorting, QuireKitTableColumn } from '@quirekit/ui';
import { QuireTable, QuirePagination, sortTableRows } from '@quirekit/ui/vue';
/** Full dataset owned by the local host, or by the simulated service. */
const tableDocuments = Array.from({ length: 18 }, (_, index) => ({
  id: `record-${index + 1}`, name: `设计记录 ${String(index + 1).padStart(2, '0')}`,
  bytes: ((index * 7) % 18 + 1) * 120, archived: index === 2
}));
/** Comparators declare actual numeric and language ordering, not display-string guesses. */
const interactionColumns: QuireKitTableColumn<(typeof tableDocuments)[number]>[] = [
  { id: 'name', title: '文档', field: 'name', rowHeader: true, compare: (a, b) => a.name.localeCompare(b.name, 'zh-CN') },
  { id: 'size', title: '大小', value: row => `${row.bytes} KB`, compare: (a, b) => a.bytes - b.bytes },
  { id: 'status', title: '状态', value: row => row.archived ? '已归档' : '可编辑' }
];

const sorting = ref<QuireKitTableSorting | null>(null);
const selected = ref<string[]>([]);
const page = ref(1);
const rows = ref<typeof tableDocuments>(tableDocuments.slice(0, 5));
const loading = ref(false);
let revision = 0;
// The displayed columns advertise requests but deliberately have no local comparator.
const columns = interactionColumns.map(({ compare: _compare, ...column }) => ({ ...column, sortable: column.id !== 'status' }));
/**
 * Simulates a server ordering full data and returning a page. No network is used.
 * @param requestedPage - Captured page at dispatch.
 * @param requestedSorting - Captured ordering at dispatch.
 * @returns One page from the simulated service.
 */
async function fetchPage(requestedPage: number, requestedSorting: QuireKitTableSorting | null): Promise<typeof tableDocuments> {
  await new Promise(resolve => setTimeout(resolve, 400));
  return sortTableRows(tableDocuments, interactionColumns, requestedSorting).slice((requestedPage - 1) * 5, requestedPage * 5);
}
watch([page, sorting], async ([requestedPage, requestedSorting]) => {
  const current = ++revision;
  loading.value = true;
  const result = await fetchPage(requestedPage, requestedSorting);
  // Only the latest request may replace the visible page or release its busy state.
  if (current !== revision) return;
  rows.value = result;
  loading.value = false;
});
onBeforeUnmount(() => { revision += 1; });
/**
 * Restarts the server query at the first page for a new ordering.
 * @param value - Requested sort state.
 */
function changeSorting(value: QuireKitTableSorting | null): void {
  sorting.value = value;
  page.value = 1;
}
</script>
<template>
  <div class="grid min-w-0 gap-qk-group p-qk-surface" data-table-remote>
    <p class="text-qk-text-secondary">模拟异步服务：请求期间保留旧行，排序与选择暂时禁用。已选 {{ selected.length }} 项。</p>
    <QuireTable v-model:selected-keys="selected" :sorting="sorting" :rows="rows" :columns="columns" row-key="id" :row-label="row => row.name" :loading="loading" label="远程分页文档" sorting-mode="manual" selectable min-width="32rem" @update:sorting="changeSorting">
      <template #footer><QuirePagination v-model:page="page" :count="tableDocuments.length" :page-size="5" :layout="['summary', 'spacer', 'previous', 'pages', 'next']" label="远程示例分页" /></template>
    </QuireTable>
  </div>
</template>
```

## 尺寸、滚动与行内操作

`size` 支持五档尺寸，默认 `sm`。`minWidth` 保留最小阅读宽度，窄容器可横向滚动；`maxHeight` 限高，`stickyHeader` 固定表头。
滚动条只在对应方向存在内容溢出时显示；内容已经完整可见时不显示滑块。
通过 `cell-列id` 插槽放置按钮，`currentRowKey` 标记当前查看的记录。

### 示例：table/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import { computed, ref } from 'vue';
import type { QuireKitTableColumn, QuireKitControlSize } from '@quirekit/ui';
import { QuireTable, QuireButton, QuirePagination, QuireSelect, QuireSwitch } from '@quirekit/ui/vue';

/** Example host data; this is not a Word document table. */
interface DocumentRow {
  /** Stable identity across paging. */
  id: string;
  /** Readable document name. */
  name: string;
  /** Responsible colleague. */
  owner: string;
  /** File size in kilobytes. */
  bytes: number;
}
const records: DocumentRow[] = Array.from({ length: 24 }, (_, index) => ({ id: `doc-${index + 1}`, name: index === 0 ? '一份标题很长、需要在单元格中自然换行而不会覆盖下一行的设计讨论记录' : `设计记录 ${index + 1}`, owner: index % 2 ? '陈清' : '林舒', bytes: 240 + index * 20 }));
const columns: QuireKitTableColumn<DocumentRow>[] = [
  { id: 'name', field: 'name', title: '文档', rowHeader: true, width: '48%' },
  { id: 'owner', field: 'owner', title: '负责人', width: '18%' },
  { id: 'size', value: row => `${row.bytes} KB`, title: '大小', align: 'end', width: '16%' },
  { id: 'actions', title: '操作', width: '18%' }
];
const page = ref(1);
const size = ref<QuireKitControlSize>('sm');
const loading = ref(false);
const empty = ref(false);
const current = ref<string | null>(null);
const rows = computed(() => empty.value ? [] : records.slice((page.value - 1) * 10, page.value * 10));
const sizes = ['xs', 'sm', 'md', 'lg', 'xl'].map(value => ({ value, label: value }));
</script>

<template>
  <div class="grid min-w-0 gap-qk-group p-qk-surface" data-table-demo>
    <div class="flex flex-wrap items-center gap-qk-surface">
      <QuireSelect v-model="size" :items="sizes" label="表格尺寸" class="w-24" />
      <QuireSwitch v-model:checked="loading" label="加载中" />
      <QuireSwitch v-model:checked="empty" label="空结果" />
    </div>
    <QuireTable :rows="rows" :columns="columns" row-key="id" label="文档目录" :size="size" :loading="loading" :current-row-key="current" sticky-header max-height="20rem" min-width="36rem">
      <template #cell-actions="{ row, size: cellSize }"><QuireButton :size="cellSize" variant="ghost" :aria-label="`查看 ${row.id}`" @click="current = row.id">查看</QuireButton></template>
      <template #footer><QuirePagination v-model:page="page" :count="empty ? 0 : records.length" :size="size" :layout="['summary', 'spacer', 'previous', 'pages', 'next']" label="文档目录分页" /></template>
    </QuireTable>
    <p class="text-qk-text-secondary">{{ current ? `正在查看 ${current}` : '查看操作只标记当前记录，不代表批量选中。' }}</p>
  </div>
</template>
```

## 加载与空态

首次加载使用 `loading` 插槽放置占位；加载结束且无记录时，默认显示 [EmptyState](/raw/components/empty-state.md) 的紧凑表格图示与标题，标题与加载播报跟随 [Locale Provider](/raw/components/locale-provider.md) 的语言，业务说明使用 `empty` 插槽。刷新已有记录时保留内容。

通过 `empty` 插槽可替换整个空态，例如使用 `scene="search"` 解释没有匹配结果，添加说明或恢复操作；需要纯文字时也可在插槽中使用不带图示的 EmptyState。

### 示例：table/states

文件：`states.vue`

```vue
<script setup lang="ts">
import { QuireEmptyState, QuireSkeleton, QuireTable } from '@quirekit/ui/vue';
const columns = [{ id: 'name', field: 'name' as const, title: '文档' }];
const rows = [{ id: 'design', name: '设计讨论记录' }];
</script>
<template>
  <div class="grid min-w-0 gap-qk-group p-qk-surface" data-table-states>
    <section class="grid min-w-0 gap-qk-inline">
      <h3>首次加载</h3>
      <QuireTable :rows="[]" :columns="columns" row-key="id" label="首次加载的文档" loading>
        <template #loading><QuireSkeleton :animated="false" /></template>
      </QuireTable>
    </section>
    <section class="grid min-w-0 gap-qk-inline">
      <h3>暂无记录</h3>
      <QuireTable :rows="[]" :columns="columns" row-key="id" label="空文档列表" />
    </section>
    <section class="grid min-w-0 gap-qk-inline">
      <h3>没有匹配结果</h3>
      <QuireTable :rows="[]" :columns="columns" row-key="id" label="没有匹配结果的文档列表">
        <template #empty>
          <QuireEmptyState
            title="没有匹配的文档"
            description="请尝试其他关键词，或调整筛选条件。"
            scene="search"
            size="sm"
            illustrated
          />
        </template>
      </QuireTable>
    </section>
    <section class="grid min-w-0 gap-qk-inline">
      <h3>刷新时保留内容</h3>
      <QuireTable :rows="rows" :columns="columns" row-key="id" label="刷新中的文档" loading />
    </section>
  </div>
</template>
```

## 插槽

`cell-列id`、`header-列id` 优先于通用 `cell`、`header`。单元格提供 `row`、`column`、`value`、`size`；自定义表头可调用 `toggleSorting`。`footer` 位于滚动区之外，适合放分页和摘要。

```vue
<QuireTable :rows="rows" :columns="columns" row-key="id" label="文档目录">
  <template #cell-actions="{ row, size }">
    <QuireButton :size="size" @click="open(row.id)">查看</QuireButton>
  </template>
</QuireTable>
```

## 键盘操作

Tab 依次访问表头操作、复选框和行内按钮。Enter 或空格切换排序与选择；普通单元格不额外进入 Tab 顺序。

## 完整数据排序函数

`sortTableRows` 从 `@quirekit/ui/vue` 导入。传入完整数据、同一份 columns 与当前 sorting；排序后再分页。函数返回新数组，保留原始行对象；`sorting: null` 保持输入顺序。参与本地排序的列必须提供 `compare`，比较结果必须是有限数值。

```ts
import type { QuireKitTableColumn, QuireKitTableSorting } from '@quirekit/ui'

declare function sortTableRows<Row>(
  rows: readonly Row[],
  columns: readonly QuireKitTableColumn<Row>[],
  sorting: QuireKitTableSorting | null
): Row[]
```

服务器只返回当前页时，由服务器排序；不要把当前页误当作完整数据交给本函数。相关列定义与排序模型见下方 API。

## API

### QuireTable

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| rows | 是 | — | Displayed page in manual mode, or complete unpaged data in local sorting mode. |
| columns | 是 | — | Ordered display columns. |
| rowKey | 是 | — | Unique stable business key. Duplicate or missing keys are rejected. |
| label | 否 | — | Accessible name when a visible caption is unnecessary. |
| labelledby | 否 | — | ID of an existing visible heading that names the table. |
| caption | 否 | — | Visible caption, also naming the table. |
| size | 否 | "sm" | Shared typography and cell spacing; rows remain naturally sized. |
| stickyHeader | 否 | false | Keep column headings within this table's scrolling viewport. |
| maxHeight | 否 | "none" | Host-selected viewport maximum height; unconstrained by default. |
| minWidth | 否 | "100%" | Host-selected minimum table width for horizontal scrolling. |
| loading | 否 | false | Loading preserves existing rows and exposes aria-busy. |
| sorting | 否 | — | Controlled single-column sorting; null explicitly means unsorted. |
| defaultSorting | 否 | — | Initial uncontrolled sorting, read only at creation. |
| sortingMode | 否 | "manual" | Manual only emits requests; local orders complete rows using column comparators. |
| selectable | 否 | false | Add a checkbox selection column; whole-row clicks do not select. |
| selectedKeys | 否 | — | Controlled selected business keys, including keys outside the displayed page. |
| defaultSelectedKeys | 否 | — | Initial uncontrolled selected keys, read only at creation. |
| rowSelectable | 否 | — | Decide which displayed rows can be toggled by the user. |
| rowLabel | 否 | — | Readable row identity in selection labels; defaults to the business key. |
| currentRowKey | 否 | — | Currently inspected row, distinct from selectable rows. |

**rows**

```ts
readonly Row[]
```

```ts
readonly (Row)[]
```

**columns**

```ts
readonly QuireKitTableColumn<Row>[]
```

```ts
readonly (QuireKitTableColumn<Row>)[]
```

**rowKey**

```ts
QuireKitTableRowKey<Row>
```

```ts
keyof Row | { (row: Row): string | number; }
```

**label**

```ts
string | undefined
```

```ts
undefined | string
```

**labelledby**

```ts
string | undefined
```

```ts
undefined | string
```

**caption**

```ts
string | undefined
```

```ts
undefined | string
```

**size**

```ts
QuireKitControlSize | undefined
```

```ts
undefined | "xs" | "sm" | "md" | "lg" | "xl"
```

**stickyHeader**

```ts
boolean | undefined
```

**maxHeight**

```ts
string | undefined
```

```ts
undefined | string
```

**minWidth**

```ts
string | undefined
```

```ts
undefined | string
```

**loading**

```ts
boolean | undefined
```

**sorting**

```ts
QuireKitTableSorting | null | undefined
```

```ts
undefined | null | {
  /** Stable column identity. */
  columnId: string;
  /** Requested ordering direction. */
  direction: "asc" | "desc";
}
```

**defaultSorting**

```ts
QuireKitTableSorting | null | undefined
```

```ts
undefined | null | {
  /** Stable column identity. */
  columnId: string;
  /** Requested ordering direction. */
  direction: "asc" | "desc";
}
```

**sortingMode**

```ts
"manual" | "local" | undefined
```

```ts
undefined | "manual" | "local"
```

**selectable**

```ts
boolean | undefined
```

**selectedKeys**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

**defaultSelectedKeys**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

**rowSelectable**

```ts
((row: Row) => boolean) | undefined
```

```ts
undefined | { (row: Row): boolean; }
```

**rowLabel**

```ts
((row: Row) => string) | undefined
```

```ts
undefined | { (row: Row): string; }
```

**currentRowKey**

```ts
string | number | null | undefined
```

```ts
undefined | null | string | number
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| update\:sorting | 否 | — |  |
| update\:selectedKeys | 否 | — |  |

**update:sorting**

```ts
[value: QuireKitTableSorting | null]
```

**update:selectedKeys**

```ts
[value: string[]]
```

#### Slots

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| cell | 否 | — | Generic fallback for every body cell. |
| header | 否 | — | Generic fallback for every header. |
| loading | 否 | — | First-load content, rendered without discarding existing rows. |
| empty | 否 | — | Empty content after loading finishes. |
| footer | 否 | — | External pagination or summary, outside the scrolling viewport. |

**cell**

```ts
QuireKitTableCellContext<Row>
```

**header**

```ts
QuireKitTableHeaderContext<Row>
```

**loading**

```ts
any
```

**empty**

```ts
any
```

**footer**

```ts
any
```

#### 公开实例成员

无。

#### 相关类型

```ts
type QuireKitTableSorting = {
  /** Stable column identity. */
  columnId: string;
  /** Requested ordering direction. */
  direction: "asc" | "desc";
};
```
