feat: migrate Toast and Table with reviewed state focus and SSR contracts

This commit is contained in:
maoyingjie
2026-10-24 07:19:26 +08:00
parent 0cfe7b6195
commit ed41af5294
95 changed files with 9358 additions and 8 deletions
+2
View File
@@ -97,8 +97,10 @@ const groups = [
{ title: "Surface 表面", url: "/components/surface" },
{ title: "Switch 开关", url: "/components/switch" },
{ title: "Tabs 标签页", url: "/components/tabs" },
{ title: "Table 表格", url: "/components/table" },
{ title: "TextArea 多行文本框", url: "/components/textarea" },
{ title: "TextField 文本输入框", url: "/components/text-field" },
{ title: "Toast 轻提示", url: "/components/toast" },
{ title: "Toolbar 工具栏", url: "/components/toolbar" },
{ title: "NumberField 数字输入框", url: "/components/number-field" },
{ title: "Slider 滑块", url: "/components/slider" },
+322
View File
@@ -0,0 +1,322 @@
---
title: Table 表格
description: 数据展示表格:排序、选择、分页与自定义单元格。
component: table
group: 组件
---
> 基于固定 HeroUI 3.2.6(ce90ea3)迁移。命名组件、作用域插槽与 DOM attrs 为 Vue 适配;预览、复制与高亮来自同一份 SFC。
## 用法
```ts
import {
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
} from "@heroui-vue/components";
```
<ComponentPreview name="table-basic" />
## 组件结构
```vue
<TableScrollContainer>
<Table>
<TableContent>
<TableHeader>
<TableRow row-key="head">
<TableColumn>商品</TableColumn>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="r in rows" :key="r.id" :row-key="r.id">
<TableCell>{{ r.name }}</TableCell>
</TableRow>
</TableBody>
</TableContent>
</Table>
</TableScrollContainer>
```
`row-key` 为稳定行标识;`disabled-keys` 禁用选择;`v-model:selected-keys` 受控选择;`v-model:sort-descriptor` 受控排序(`aria-sort` 同步)。
## 示例
### 次要变体
<ComponentPreview name="table-secondary-variant" />
### 异步加载
<ComponentPreview name="table-async-loading" />
### 排序
<ComponentPreview name="table-sorting" />
### 选择
<ComponentPreview name="table-selection" />
### 可展开行
<ComponentPreview name="table-expandable-rows" />
### 分页
<ComponentPreview name="table-pagination" />
### 列宽调整
<ComponentPreview name="table-column-resizing" />
### 空状态
<ComponentPreview name="table-empty-state" />
### 虚拟滚动
<ComponentPreview name="table-virtualization" />
### TanStack Table
<ComponentPreview name="table-tanstack-table" />
### 自定义单元格
<ComponentPreview name="table-custom-cells" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="table-custom-styles" />
### 全局 CSS
```css
@layer components {
.hv-table {
@apply rounded-2xl;
}
.hv-table__column {
@apply text-xs font-semibold;
}
.hv-table__row {
@apply transition-colors;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
### CSS 类
Table 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960/packages/styles/components/table.css)):
#### 基础类
- `.hv-table-root` - 根容器(命名为 `hv-table-root` 而非 `hv-table`,因为 `hv-table` 是 Tailwind CSS 内置的 `display: table` 工具类)
- `.hv-table__scroll-container` - 横向滚动包裹层与自定义滚动条
- `.hv-table__content` - `` 元素
- `.hv-table__header` - 表头行(``)
- `.hv-table__column` - 列表头单元格(``)
- `.hv-table__body` - 表体(``)
- `.hv-table__row` - 行(``)
- `.hv-table__cell` - 数据单元格(``)
- `.hv-table__footer` - 表底容器(位于 table 外部)
#### 进阶类
- `.hv-table__column-resizer` - 列宽拖拽手柄
- `.hv-table__resizable-container` - 启用列宽调整的包裹层
- `.hv-table__load-more` - 无限滚动的哨兵行
- `.hv-table__load-more-content` - 加载指示器的样式容器
- `.hv-table__sortable-column-header` - 可排序列标签与指示器的包裹层
- `.hv-table__sortable-column-indicator` - 排序方向 chevron(通过 `[data-direction="descending"]` 翻转)
#### 变体类
- `.hv-table-root--primary` - 灰色背景容器与卡片式表体(默认)
- `.hv-table-root--secondary` - 无背景,独立圆角表头
### 交互状态
Table 同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制:
- **悬停**:`:hover` 或 `[data-hover="true"]`(行背景变化)
- **已选中**:`[data-selected="true"]`(行高亮)
- **聚焦**:`:focus-visible` 或 `[data-focus-visible="true"]`(行、列与单元格的内嵌焦点环)
- **禁用**:`:disabled` 或 `[aria-disabled="true"]`(降低透明度)
- **可排序**:`[data-allows-sorting="true"]`(列上的交互指针样式)
- **拖动中**:`[data-dragging="true"]`(降低透明度)
- **放置目标**:`[data-drop-target="true"]`(强调色背景)
## API 参考
所有展示部件接受 `class`、`style`、ARIA 与原生事件,默认插槽渲染内容。`TableKey = string | number`,数字和字符串 key 不等价,空字符串有效。Vue 使用数组模型,不使用 React Aria 的 Selection、Collection 或 TableLayout 实例。
### Table / TableRoot
| Prop | 类型 | 默认值 | 描述 |
| --------- | -------------------------- | ----------- | ------------ |
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 容器与行外观 |
| `as` | `string` | `'div'` | 根标签 |
### TableScrollContainer
| Prop | 类型 | 默认值 | 描述 |
| ---- | -------- | ------- | ---------------------------------------- |
| `as` | `string` | `'div'` | 滚动容器;通过 class 设置宽高和 overflow |
### TableContent
| Prop | 类型 | 默认值 | 描述 |
| ------------------------------------------ | ---------------------------------------------------------------------------- | ---------- | ---------------------------------------------- |
| `as` | `string` | `'table'` | 语义表格根 |
| `selectionMode` | `'none' \| 'single' \| 'multiple'` | `'none'` | 选择模式 |
| `selectedKeys` / `defaultSelectedKeys` | `TableKey[]` | — / `[]` | 受控 / 非受控初始选择 |
| `disabledKeys` | `TableKey[]` | `[]` | 禁用行 |
| `sortDescriptor` / `defaultSortDescriptor` | `{column: string, direction: 'ascending' \| 'descending' \| 'none'} \| null` | — / `null` | 受控 / 初始排序;数据排序由调用方处理 |
| `expandedKeys` / `defaultExpandedKeys` | `TableKey[]` | — / `[]` | 受控 / 初始树行展开集合 |
| `treeColumn` | `string` | — | 树形列 id,只有对应单元格 isTreeColumn 为 true |
| `rowKeys` | `TableKey[]` | 当前挂载行 | 虚拟场景传逻辑行全集,用于范围、全选与焦点导航 |
| 事件 | 参数 | 描述 |
| ----------------------------------------- | -------------------------------- | ---------------------------------------------------------------------- |
| `update:selectedKeys` / `selectionChange` | `TableKey[]` | 选择提案;父组件拒绝后允许相同提案重试 |
| `update:sortDescriptor` / `sortChange` | 排序描述符 | 排序提案 |
| `update:expandedKeys` / `expandedChange` | `TableKey[]` | 展开提案 |
| `focusRow` | `(key: TableKey, index: number)` | 导航到未挂载的逻辑行时请求滚动;处理器同步更新可见窗口,下一 tick 聚焦 |
### TableHeader
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| -------------- | -------- | ------------------ | ------------------------------------------ |
| `as` / `rowAs` | `string` | `'thead'` / `'tr'` | 自动创建表头行,默认插槽直接放 TableColumn |
| 默认插槽 | 列内容 | — | 动态列用 v-for;不要再嵌套一层 tr |
### TableColumn
| Prop / 事件 | 类型 | 默认值 | 描述 |
| ------------------------------- | ------------------ | ------- | ----------------------------------------- |
| `as` | `string` | `'th'` | 列头标签,scope=col |
| `id` | `string` | — | 排序与树形列 id |
| `allowsSorting` / `isRowHeader` | `boolean` | `false` | 排序列 / 对应正文单元格为 th[scope=row] |
| `width` / `defaultWidth` | `number \| string` | — | 受控宽度 / 非受控初始宽度,数字为 px |
| `minWidth` / `maxWidth` | `number` | — | 宽度上下限,优先于 Resizer 的缺省边界 |
| `update:width` | `number` | — | 拖动/键盘提出的宽度,可使用 v-model:width |
| 默认插槽 | 内容 | — | 列标签及排序、调整手柄 |
### TableBody
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| ----------- | -------- | --------- | ---------------------------------------------------------- |
| `as` | `string` | `'tbody'` | 正文根 |
| 默认插槽 | 行内容 | — | 动态行使用 v-for;空状态使用 colspan 单元格组合 EmptyState |
### TableRow
| Prop | 类型 | 默认值 | 描述 |
| --------------- | ---------- | ------- | ------------------------------ |
| `as` | `string` | `'tr'` | 行标签 |
| `rowKey` | `TableKey` | 必填 | 稳定逻辑 key;代替 React 的 id |
| `isDisabled` | `boolean` | `false` | 行禁用,不抢子控件事件 |
| `level` | `number` | — | 树形行层级,从 1 开始 |
| `hasChildItems` | `boolean` | `false` | 是否有树子项 |
| 作用域插槽状态 | 类型 | 描述 |
| ------------------------------ | ------------ | ------------------------------ |
| `isSelected` / `isDisabled` | `boolean` | 已接受选择 / 禁用状态 |
| `toggleExpanded` | `() => void` | 提交展开切换提案,禁用行不响应 |
| `isExpanded` / `hasChildItems` | `boolean` | 展开 / 子项状态 |
### TableCell
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| ----------- | ------------------------------------------------------------------- | ------ | ------------------ |
| `as` | `string` | `'td'` | 行表头列自动为 th |
| `colspan` | `number \| string` | — | 横跨列数 |
| 默认插槽 | `{isSelected, isDisabled, isExpanded, hasChildItems, isTreeColumn}` | — | 状态来自行及对应列 |
### TableSortableColumnHeader
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| --------------- | ------------ | -------------- | ------------------------------------ |
| `as` | `string` | `'span'` | 包裹标签 |
| `columnKey` | `string` | 继承列 id | 排序列标识 |
| `sortDirection` | 排序方向 | 继承对应列状态 | 显式方向优先 |
| `showIndicator` | `boolean` | `true` | 已排序时显示指示器 |
| `indicator` | `VNodeChild` | 默认 chevron | 自定义指示器 |
| `isDisabled` | `boolean` | `false` | 禁用排序按钮 |
| 默认插槽 | 内容 | — | 列标签;内部原生按钮支持 Enter/Space |
### TableFooter
| Prop | 类型 | 默认值 | 描述 |
| ---- | -------- | ------- | ----------------------------------- |
| `as` | `string` | `'div'` | 放在 Content 外的表格底部,例如分页 |
### TableColumnResizer
| Prop | 类型 | 默认值 | 描述 |
| ----------------------- | -------- | ------------ | --------------------------------------- |
| `as` | `string` | `'div'` | 可聚焦 separator 手柄 |
| `minWidth` / `maxWidth` | `number` | `48` / `640` | 列未指定时的边界,px |
| `step` | `number` | `8` | 方向键步长;Shift 四倍;Home/End 到边界 |
拖动方向遵循 RTL。pointercancel、捕获丢失、Escape、节点替换和卸载终止手势;取消恢复起始宽度。正常 pointerup 保留接受值。宽度受控时只提交提案,不越过父组件直接改 DOM。
### TableResizableContainer
| Prop | 类型 | 默认值 | 描述 |
| ---- | -------- | ------- | ---------------------------------------- |
| `as` | `string` | `'div'` | 调整表格的布局容器;宽度状态在 Column 上 |
### TableLoadMoreItem / TableLoadMore
| Prop / 事件 | 类型 | 默认值 | 描述 |
| -------------- | ------------- | -------------------- | ---------------------------------------------- |
| `as` | `string` | `'tr'` | 加载哨兵行 |
| `isLoading` | `boolean` | `false` | 正在加载;一次加载完成后可继续请求 |
| `hasMore` | `boolean` | `true` | 是否还有数据 |
| `colspan` | `number` | `100` | 自动生成的加载单元格跨列数 |
| `scrollOffset` | `number` | `0` | 触发提前量,px |
| `scrollRoot` | `HTMLElement` | 最近 ScrollContainer | 观察的滚动视口 |
| `loadMore` | 无参数 | — | 哨兵进入视口时请求一次;同次在途加载不重复触发 |
### TableLoadMoreContent
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| ----------- | -------- | ------- | ------------------------------------- |
| `as` | `string` | `'div'` | 加载内容容器,Item 自动创建整行单元格 |
| 默认插槽 | 内容 | — | Spinner 或自定义加载提示 |
### TableCollection
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| ----------- | --------------- | --------------- | -------------------------------------------- |
| `items` | `unknown[]` | `[]` | 待渲染数据 |
| `as` | `string` | 无标签 Fragment | 可选包裹标签;默认可在 tr 内与静态单元格并存 |
| 默认插槽 | `{item, index}` | — | 渲染条目;稳定 key 放在生成的 Row/Cell 上 |
### TableLayout 与 Vue 虚拟滚动
未导出 React Aria TableLayout 类。示例使用固定 48px 行高、320px 滚动视口和 overscan 窗口,按完整 rowKeys 处理键盘请求;aria-rowcount 包括表头,aria-rowindex 为逻辑位置。仅当前窗口挂载。可变高度、拖放指标与 RAC 虚拟布局扩展暂不支持,不能把固定行高示例用于多行自动换高的数据。TanStack 示例使用可选 table-core 数据模型,库运行时不依赖它。
## 无障碍
使用原生 table/thead/tbody/th/td,Content 为 grid(树形为 treegrid),行表头 scope=row,排序 aria-sort,选择 aria-selected,禁用 aria-disabled。行使用单一 Tab 入口;上下键跨行、左右键跨单元格,Home/End 到行首尾,Ctrl/Meta+Home/End 到全集首尾。Space 切换选择,Shift 点击/导航扩展范围,Ctrl/Meta+A 多选全选;按钮、链接和输入控件保留自己的键盘行为。虚拟数据需要完整 rowKeys、行索引及 focusRow 回调。
## 相关组件
- [Pagination 分页](./pagination)
- [Button 按钮](./button)
+274
View File
@@ -0,0 +1,274 @@
---
title: Toast 轻提示
description: 向用户展示临时通知与消息,支持自动消失与可定制的放置位置。
component: toast
group: 组件
---
> 基于固定 HeroUI 3.2.6(ce90ea3)迁移。命名组件、作用域插槽与 DOM attrs 为 Vue 适配;预览、复制与高亮来自同一份 SFC。
## 用法
```ts
import {
ToastProvider,
createToastFunction,
ToastQueue,
} from "@heroui-vue/components";
```
<ComponentPreview name="toast-default" />
## 组件结构
`ToastProvider` 渲染通知区域;`ToastQueue` 管理计时与退出生命周期。默认 `timeout=4000`、`gap=12`、可视上限 `3`、宽度 `460`、热键 `Alt+T`、退出保留 `300ms`。**可视上限不删除队列中的旧通知**,只是隐藏并继续计时。
```vue
<ToastProvider :queue="queue" to="body">
<template #default="{ toast: item, close }">
<ToastIndicator :variant="item.variant" />
<ToastContent>
<ToastTitle>{{ item.title }}</ToastTitle>
<ToastDescription>{{ item.description }}</ToastDescription>
</ToastContent>
<ToastCloseButton @click="close" />
</template>
</ToastProvider>
```
不提供插槽时使用完整默认渲染;正文容器只包标题和说明,指示器、动作与关闭按钮为同级。自定义完整卡片样式通过 `toast-class` 传给 Provider 自动创建的 Toast 根节点。客户端可在应用根挂载一个默认 Provider,使用全局 `toast`;独立演示使用自己的队列,退出页面时销毁。
`toast()` 返回稳定 key;`toast.update(id, …)` 原位更新;`toast.promise(…)` 就地结算;`timeout: 0` 保持打开。
## 示例
### 变体
<ComponentPreview name="toast-variants" />
### 放置位置
<ComponentPreview name="toast-placements" />
### 展开堆叠
<ComponentPreview name="toast-expanded" />
### 简单 Toast
<ComponentPreview name="toast-simple" />
### 自定义指示器
<ComponentPreview name="toast-custom-indicator" />
### 自定义 Toast 渲染
<ComponentPreview name="toast-custom-toast" />
### Promise 与加载中
<ComponentPreview name="toast-promise" />
### 回调
<ComponentPreview name="toast-callbacks" />
### 自定义队列
<ComponentPreview name="toast-custom-queue" />
### 配置
`timeout` 默认 4000ms;`0` 持久显示。悬停、焦点进入、页面隐藏和外部暂停分别管理,全部原因解除后继续剩余时间。可视上限隐藏旧消息但不删除、不停止它们的倒计时。
## 自定义样式
### Tailwind CSS
<ComponentPreview name="toast-custom-styles" />
### 全局 CSS
```css
@layer components {
.hv-toast {
@apply rounded-2xl border border-border;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
### CSS 类
Toast 使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960/packages/styles/components/toast.css)):
#### 基础类
- `.hv-toast` — Toast 根容器
- `.hv-toast-region` — Toast 区域容器
- `.hv-toast__content` — 包裹标题与说明的内容容器
- `.hv-toast__indicator` — 图标/指示器容器
- `.hv-toast__title` — Toast 标题文本
- `.hv-toast__description` — Toast 说明文本
- `.hv-toast__action` — 操作按钮容器
- `.hv-toast__close-button` — 关闭按钮容器
#### 变体类
- `.hv-toast--default` — 默认灰色变体
- `.hv-toast--accent` — 强调蓝色变体
- `.hv-toast--success` — 成功绿色变体
- `.hv-toast--warning` — 警告黄/橙色变体
- `.hv-toast--danger` — 危险红色变体
### 交互状态
组件支持多种状态:
- **最前**:`[data-frontmost]` — 应用于堆叠中最上层可见的 Toast
- **索引**:`[data-index]` — 基于 Toast 在堆叠中的位置
- **放置**:`[data-placement="*"]` — 基于 Toast 区域的放置位置
- **进入中**:`[data-entering]` — Toast 首次绘制时应用
- **退出中**:`[data-exiting]` — 关闭中的 Toast 播放退出过渡时应用
- **展开**:`[data-expanded]` — 堆叠展开时应用于每个 Toast
- **隐藏**:`[data-hidden]` — 应用于超出 `maxVisibleToasts` 的 Toast
## API 参考
所有部件接受 `class`、`style`、ARIA 和原生 DOM 事件,透传到自身根节点。文本内容支持 Vue `VNodeChild`,也可用具名导出部件与默认插槽组织内容。
### ToastProvider
| Prop | 类型 | 默认值 | 描述 |
| ------------------ | --------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------- |
| `placement` | `'top start' \| 'top' \| 'top end' \| 'bottom start' \| 'bottom' \| 'bottom end'` | `'bottom'` | 区域位置 |
| `gap` | `number` | `12` | 展开间距,px |
| `isExpanded` | `boolean` | `false` | 固定展开,不单独暂停计时 |
| `maxVisibleToasts` | `number` | 队列上限,默认 `3` | 只影响可见数量 |
| `hotkey` | `string[]` | `['altKey','KeyT']` | 修饰键需精确匹配,非修饰键用 event.code;`[]` 禁用 |
| `scaleFactor` | `number` | `0.05` | 折叠堆叠缩放系数 |
| `width` | `number \| string` | `460` | 宽度,数字按 px |
| `queue` | `ToastQueue<ToastContentValue>` | 客户端共享 `toastQueue` | 自定义队列;服务端缺省使用请求局部空队列 |
| `to` | `string \| HTMLElement` | — | Vue Teleport 目标;文档演示使用 `body` 避免预览容器裁切 |
| `toastClass` | `string` | — | 自动创建的每条 Toast 根节点的附加类 |
| 插槽 / 暴露方法 | 值 | 描述 |
| --------------- | ------------------------------------------------- | -------------------------------------- |
| 默认插槽 | `{ toast: ToastContentValue, close: () => void }` | 自定义根内部内容;缺省渲染完整默认布局 |
| `queue` | 当前队列实例 | 随 queue prop 替换 |
| `toast()` | `ToastFn` | 返回绑定当前队列的命令式方法 |
### Toast / ToastRoot
| Prop | 类型 | 默认值 | 描述 |
| ------------- | ------------------------------------------------------------- | -------------------- | --------------------------------------- |
| `toastKey` | `string` | 必填 | 队列返回的 key |
| `scaleFactor` | `number` | 继承 Provider | 可覆盖缩放系数 |
| `index` | `number` | 必填 | 根在队列中的位置,Provider 自动传入 |
| `content` | `ToastContentValue` | `{}` | 标题、说明、指示器、动作、变体、loading |
| `variant` | `'default' \| 'accent' \| 'success' \| 'warning' \| 'danger'` | 内容变体或 `default` | 视觉变体 |
| `placement` | 与 Provider 相同 | 继承 Provider | 放置位置 |
| 默认插槽 | `{ toast, close }` | — | 自定义内容 |
### ToastContent
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| ----------- | -------- | ------- | ---------- |
| `as` | `string` | `'div'` | 根标签 |
| 默认插槽 | 内容 | — | 标题和说明 |
### ToastIndicator
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| ----------- | ------------- | ----------- | --------------------------------------------- |
| `variant` | 与 Toast 相同 | `'default'` | 默认图标变体 |
| 默认插槽 | 内容 | 变体图标 | 替换默认指示器;命令式 `indicator: null` 隐藏 |
### ToastTitle
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| ----------- | -------- | ------- | -------- |
| `as` | `string` | `'div'` | 根标签 |
| 默认插槽 | 内容 | — | 通知标题 |
### ToastDescription
| Prop / 插槽 | 类型 | 默认值 | 描述 |
| ----------- | -------- | ------- | -------- |
| `as` | `string` | `'div'` | 根标签 |
| 默认插槽 | 内容 | — | 通知说明 |
### ToastActionButton
| Prop / 事件 | 类型 | 默认值 | 描述 |
| ---------------------------- | ------------ | ------------- | --------------------------------------------------------------- |
| `variant` | Button 变体 | `'secondary'` | 按钮变体 |
| `size` | Button 尺寸 | `'sm'` | 按钮尺寸 |
| `isDisabled` | `boolean` | `false` | 禁用 |
| `@click` | `MouseEvent` | — | 默认命令式动作先调用用户处理,再关闭;preventDefault 可阻止关闭 |
| 其余 Button props / 默认插槽 | 见 Button | — | 透传给基础 Button;自定义插槽中的按钮可调用 close |
### ToastCloseButton
| Prop / 事件 | 类型 | 默认值 | 描述 |
| ---------------------------- | -------------- | ------- | --------------------------------------------------------- |
| `isDisabled` | `boolean` | `false` | 禁用关闭 |
| CloseButton props / 默认插槽 | 见 CloseButton | — | 透传;默认渲染已绑定关闭,自定义插槽使用 `@click="close"` |
### ToastQueue
| 构造选项 | 类型 | 默认值 | 描述 |
| ------------------ | -------------------------- | -------- | ------------------------------------ |
| `exitDuration` | `number` | `300` | 退出保留毫秒数;0 或减少动画立即移除 |
| `maxVisibleToasts` | `number` | `3` | Provider 缺省可视上限,不删除旧条目 |
| `wrapUpdate` | `(fn: () => void) => void` | 直接运行 | 包裹通知更新 |
| 方法 / 属性 | 类型 | 描述 |
| ---------------------------------------- | --------------------- | ------------------------------------------------------------------------- |
| `add(content, options?)` | 返回 `string` key | options 为 `{timeout?, onClose?}` |
| `update(key, content, options?)` | 返回 `boolean` | 原位更新;省略 timeout 保持剩余计时,0 取消计时;不存在或退出中返回 false |
| `close(key)` / `clear()` | `void` | 开始退出,onClose 至多一次 |
| `pauseAll()` / `resumeAll()` | `void` | 外部暂停/恢复,不解除悬停、焦点或页面隐藏暂停 |
| `visibleToasts` | `QueuedToast<T>[]` | 包含尚未卸载的全部条目,最新在前 |
| `getExitingKeys()` | `ReadonlySet<string>` | 当前退出 key |
| `subscribe(fn)` / `subscribeExiting(fn)` | 返回取消订阅函数 | 内容与退出状态订阅 |
| `destroy()` | `void` | 清理计时器与订阅;实例不再接受新消息 |
### toast 函数 / createToastFunction(queue)
客户端共享 `toast` 与工厂返回的 `ToastFn` 具有同样方法。`toast(message, options?)`、`success`、`info`、`warning`、`danger`、`update(key,message,options?)`、`promise` 均返回 key;`close`、`clear`、`pauseAll`、`resumeAll` 返回 void。`update` 的目标不存在时创建新通知;Promise 结算只修改仍存活且未被显式替换的原条目。
| Option | 类型 | 默认值 | 描述 |
| --------------------------- | -------------------------------------- | ----------- | ----------------------------------------- |
| 首个 `message` 参数 | `VNodeChild` | — | 标题 |
| `description` / `indicator` | `VNodeChild` | — | 说明 / 自定义图标;indicator 为 null 隐藏 |
| `variant` | Toast 变体 | `'default'` | 外观 |
| `actionProps` | `ButtonProps & { label?: VNodeChild }` | — | 按钮内容使用 label;事件使用 onClick |
| `isLoading` | `boolean` | `false` | 用 Spinner 替代默认指示器 |
| `timeout` | `number` | `4000` | 自动关闭时间;0 持久显示 |
| `onClose` | `() => void` | — | 关闭开始时回调 |
### toast.promise Options
| Option | 类型 | 描述 |
| --------- | ---------------------------------------------- | --------------------------------- |
| `loading` | `VNodeChild` | 等待消息 |
| `success` | `VNodeChild \| ((data: T) => VNodeChild)` | 成功消息,保留 Promise 值类型推断 |
| `error` | `VNodeChild \| ((error: Error) => VNodeChild)` | 失败消息 |
## 无障碍
区域使用 region 和可覆盖的 aria-label;通知使用 status。Alt+T 进入有消息的堆叠,Escape 返回之前的触发器;关闭当前条目时聚焦邻近存活条目,最后一条关闭后返回触发器。隐藏、退出与折叠的非首条通知设置 inert,内部按钮不能进入 Tab 顺序。悬停、焦点进入、页面隐藏暂停倒计时。
### 上游差异与 SSR
React 对象部件改具名导出,ReactNode 改 VNodeChild,onPress 改 DOM click;Provider 自动创建 Toast 根,作用域插槽负责内部内容,toastClass 定制根样式。采用单一自有队列计时,未运行 React,也未另启 Reka 的第二个倒计时。服务端全局 toast 为无操作,不保留跨请求消息;SSR 如需通知内容,每请求创建 ToastQueue 并传入 Provider,客户端沿用该请求数据,使用后 destroy。Teleport SSR 目标请依 Vue SSR 规则在客户端装载。
## 相关组件
- [Button 按钮](./button)
- [Spinner 加载指示器](./spinner)
+191
View File
@@ -0,0 +1,191 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from "vue";
import {
Chip,
Spinner,
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
TableLoadMoreItem,
TableLoadMoreContent,
} from "@heroui-vue/components";
interface User {
id: number;
name: string;
role: string;
status: string;
email: string;
}
const statusColorMap: Record<string, "success" | "danger" | "warning"> = {
休假: "warning",
在职: "success",
未激活: "danger",
};
const allUsers: User[] = [
{
email: "kate@acme.com",
id: 1,
name: "Kate Moore",
role: "首席执行官",
status: "在职",
},
{
email: "john@acme.com",
id: 2,
name: "John Smith",
role: "首席技术官",
status: "在职",
},
{
email: "sara@acme.com",
id: 3,
name: "Sara Johnson",
role: "首席营销官",
status: "休假",
},
{
email: "michael@acme.com",
id: 4,
name: "Michael Brown",
role: "首席财务官",
status: "在职",
},
{
email: "emily@acme.com",
id: 5,
name: "Emily Davis",
role: "产品经理",
status: "未激活",
},
{
email: "davis@acme.com",
id: 6,
name: "Davis Wilson",
role: "首席设计师",
status: "在职",
},
{
email: "olivia@acme.com",
id: 7,
name: "Olivia Martinez",
role: "前端工程师",
status: "在职",
},
{
email: "james@acme.com",
id: 8,
name: "James Taylor",
role: "后端工程师",
status: "在职",
},
{
email: "sophia@acme.com",
id: 9,
name: "Sophia Anderson",
role: "测试工程师",
status: "休假",
},
{
email: "liam@acme.com",
id: 10,
name: "Liam Thomas",
role: "DevOps 工程师",
status: "在职",
},
{
email: "lucas@acme.com",
id: 11,
name: "Lucas Martinez",
role: "产品经理",
status: "在职",
},
{
email: "emma@acme.com",
id: 12,
name: "Emma Johnson",
role: "前端工程师",
status: "在职",
},
];
const ITEMS_PER_PAGE = 6;
const columns = [
{ id: "name", name: "姓名" },
{ id: "role", name: "角色" },
{ id: "status", name: "状态" },
{ id: "email", name: "邮箱" },
];
const items = ref<User[]>(allUsers.slice(0, ITEMS_PER_PAGE));
const isLoading = ref(false);
const hasMore = computed(() => items.value.length < allUsers.length);
let timer: ReturnType<typeof setTimeout> | undefined;
onBeforeUnmount(() => clearTimeout(timer));
function loadMore() {
if (!hasMore.value || isLoading.value) return;
isLoading.value = true;
// Demo-only simulated fetch.
timer = setTimeout(() => {
items.value = allUsers.slice(0, items.value.length + ITEMS_PER_PAGE);
isLoading.value = false;
}, 1500);
}
</script>
<template>
<Table>
<TableScrollContainer class="h-[280px] overflow-y-auto">
<TableContent aria-label="异步加载表格" class="min-w-[600px]">
<TableHeader class="sticky top-0 z-10 bg-surface-secondary">
<TableColumn
v-for="col in columns"
:key="col.id"
:id="col.id"
:is-row-header="col.id === 'name'"
>
{{ col.name }}
</TableColumn>
</TableHeader>
<TableBody>
<TableRow
v-for="user in items"
:key="user.id"
:row-key="String(user.id)"
>
<TableCell>{{ user.name }}</TableCell>
<TableCell>{{ user.role }}</TableCell>
<TableCell>
<Chip
:color="statusColorMap[user.status]"
size="sm"
variant="soft"
>
{{ user.status }}
</Chip>
</TableCell>
<TableCell>{{ user.email }}</TableCell>
</TableRow>
<TableLoadMoreItem
v-if="hasMore"
:is-loading="isLoading"
:scroll-offset="0"
@load-more="loadMore"
>
<TableLoadMoreContent>
<Spinner size="md" />
</TableLoadMoreContent>
</TableLoadMoreItem>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>
+53
View File
@@ -0,0 +1,53 @@
<script setup lang="ts">
import {
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
</script>
<template>
<Table>
<TableScrollContainer>
<TableContent aria-label="团队成员" class="min-w-[600px]">
<TableHeader>
<TableColumn is-row-header>姓名</TableColumn>
<TableColumn>角色</TableColumn>
<TableColumn>状态</TableColumn>
<TableColumn>邮箱</TableColumn>
</TableHeader>
<TableBody>
<TableRow row-key="1">
<TableCell>Kate Moore</TableCell>
<TableCell>首席执行官</TableCell>
<TableCell>在职</TableCell>
<TableCell>kate@acme.com</TableCell>
</TableRow>
<TableRow row-key="2">
<TableCell>John Smith</TableCell>
<TableCell>首席技术官</TableCell>
<TableCell>在职</TableCell>
<TableCell>john@acme.com</TableCell>
</TableRow>
<TableRow row-key="3">
<TableCell>Sara Johnson</TableCell>
<TableCell>首席营销官</TableCell>
<TableCell>休假</TableCell>
<TableCell>sara@acme.com</TableCell>
</TableRow>
<TableRow row-key="4">
<TableCell>Michael Brown</TableCell>
<TableCell>首席财务官</TableCell>
<TableCell>在职</TableCell>
<TableCell>michael@acme.com</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>
+83
View File
@@ -0,0 +1,83 @@
<script setup lang="ts">
import {
Chip,
Table,
TableBody,
TableCell,
TableColumn,
TableColumnResizer,
TableContent,
TableHeader,
TableRow,
TableResizableContainer,
TableScrollContainer,
} from "@heroui-vue/components";
</script>
<template>
<Table>
<TableResizableContainer>
<TableScrollContainer>
<TableContent aria-label="可调整列宽的表格" class="min-w-[700px]">
<TableHeader>
<TableColumn id="name" is-row-header :min-width="160">
姓名
<TableColumnResizer />
</TableColumn>
<TableColumn id="role" :min-width="220">
角色
<TableColumnResizer />
</TableColumn>
<TableColumn id="status" :min-width="100">
状态
<TableColumnResizer />
</TableColumn>
<TableColumn id="email" :min-width="200">邮箱</TableColumn>
</TableHeader>
<TableBody>
<TableRow row-key="1">
<TableCell>Kate Moore</TableCell>
<TableCell>首席执行官</TableCell>
<TableCell>
<Chip color="success" size="sm" variant="soft">Active</Chip>
</TableCell>
<TableCell>kate@acme.com</TableCell>
</TableRow>
<TableRow row-key="2">
<TableCell>John Smith</TableCell>
<TableCell>首席技术官</TableCell>
<TableCell>
<Chip color="success" size="sm" variant="soft">Active</Chip>
</TableCell>
<TableCell>john@acme.com</TableCell>
</TableRow>
<TableRow row-key="3">
<TableCell>Sara Johnson</TableCell>
<TableCell>首席营销官</TableCell>
<TableCell>
<Chip color="warning" size="sm" variant="soft">On Leave</Chip>
</TableCell>
<TableCell>sara@acme.com</TableCell>
</TableRow>
<TableRow row-key="4">
<TableCell>Michael Brown</TableCell>
<TableCell>首席财务官</TableCell>
<TableCell>
<Chip color="success" size="sm" variant="soft">Active</Chip>
</TableCell>
<TableCell>michael@acme.com</TableCell>
</TableRow>
<TableRow row-key="5">
<TableCell>Emily Davis</TableCell>
<TableCell>产品经理</TableCell>
<TableCell>
<Chip color="danger" size="sm" variant="soft">Inactive</Chip>
</TableCell>
<TableCell>emily@acme.com</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
</TableResizableContainer>
</Table>
</template>
+271
View File
@@ -0,0 +1,271 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Avatar,
AvatarFallback,
AvatarImage,
Button,
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Chip,
Table,
type TableKey,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
TableSortableColumnHeader,
} from "@heroui-vue/components";
import { IconCopy, IconEye, IconPencil, IconTrash } from "@tabler/icons-vue";
interface User {
id: number;
name: string;
image_url: string;
role: string;
status: "在职" | "未激活" | "休假";
email: string;
}
const statusColorMap: Record<string, "success" | "danger" | "warning"> = {
休假: "warning",
在职: "success",
未激活: "danger",
};
const users: User[] = [
{
email: "kate@acme.com",
id: 4586932,
image_url:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/red.jpg",
name: "Kate Moore",
role: "首席执行官",
status: "在职",
},
{
email: "john@acme.com",
id: 5273849,
image_url:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
name: "John Smith",
role: "首席技术官",
status: "在职",
},
{
email: "sara@acme.com",
id: 7492836,
image_url:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
name: "Sara Johnson",
role: "首席营销官",
status: "休假",
},
{
email: "michael@acme.com",
id: 8293746,
image_url:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
name: "Michael Brown",
role: "首席财务官",
status: "在职",
},
{
email: "emily@acme.com",
id: 1234567,
image_url:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/orange.jpg",
name: "Emily Davis",
role: "产品经理",
status: "未激活",
},
];
const selectedKeys = ref<TableKey[]>([]);
const sortDescriptor = ref<{
column: string;
direction: "ascending" | "descending";
}>({
column: "name",
direction: "ascending",
});
const sortedUsers = computed(() => {
const col = sortDescriptor.value.column as keyof User;
return [...users].sort((a, b) => {
let cmp = String(a[col]).localeCompare(String(b[col]));
if (sortDescriptor.value.direction === "descending") cmp *= -1;
return cmp;
});
});
function dirOf(id: string): "ascending" | "descending" | undefined {
return sortDescriptor.value.column === id
? sortDescriptor.value.direction
: undefined;
}
function onSortChange(
d: { column: string; direction: "ascending" | "descending" | "none" } | null,
) {
if (d && d.direction !== "none") {
sortDescriptor.value = { column: d.column, direction: d.direction };
}
}
function initials(name: string) {
return name
.split(" ")
.map((n) => n[0])
.join("");
}
</script>
<template>
<Table>
<TableScrollContainer>
<TableContent
aria-label="自定义单元格表格"
class="min-w-[800px]"
selection-mode="multiple"
:selected-keys="selectedKeys"
:sort-descriptor="sortDescriptor"
@update:selected-keys="(k: TableKey[]) => (selectedKeys = k)"
@update:sort-descriptor="onSortChange"
>
<TableHeader>
<TableColumn class="pe-0">
<Checkbox aria-label="全选">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
</CheckboxContent>
</Checkbox>
</TableColumn>
<TableColumn
id="id"
allows-sorting
is-row-header
class="after:hidden"
>
<TableSortableColumnHeader :sort-direction="dirOf('id')">
员工 ID
</TableSortableColumnHeader>
</TableColumn>
<TableColumn id="name" allows-sorting>
<TableSortableColumnHeader :sort-direction="dirOf('name')">
成员
</TableSortableColumnHeader>
</TableColumn>
<TableColumn id="role" allows-sorting>
<TableSortableColumnHeader :sort-direction="dirOf('role')">
角色
</TableSortableColumnHeader>
</TableColumn>
<TableColumn id="status" allows-sorting>
<TableSortableColumnHeader :sort-direction="dirOf('status')">
状态
</TableSortableColumnHeader>
</TableColumn>
<TableColumn class="text-end">操作</TableColumn>
</TableHeader>
<TableBody>
<TableRow
v-for="user in sortedUsers"
:key="user.id"
:row-key="String(user.id)"
>
<TableCell class="pe-0">
<Checkbox
:aria-label="`选择 ${user.name}`"
variant="secondary"
:is-selected="selectedKeys.includes(String(user.id))"
@update:checked="
() => {
const id = String(user.id);
selectedKeys = selectedKeys.includes(id)
? selectedKeys.filter((k) => k !== id)
: [...selectedKeys, id];
}
"
>
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
</CheckboxContent>
</Checkbox>
</TableCell>
<TableCell class="font-medium">
<div class="flex items-center gap-2">
#{{ user.id }}
<Button
is-icon-only
:aria-label="`复制 ID #${user.id}`"
size="sm"
variant="ghost"
>
<IconCopy class="size-4 text-muted" aria-hidden="true" />
</Button>
</div>
</TableCell>
<TableCell>
<div class="flex items-center gap-3">
<Avatar size="sm">
<AvatarImage :src="user.image_url" />
<AvatarFallback>{{ initials(user.name) }}</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<span class="text-xs">{{ user.name }}</span>
<span class="text-xs text-muted">{{ user.email }}</span>
</div>
</div>
</TableCell>
<TableCell class="min-w-52">{{ user.role }}</TableCell>
<TableCell class="min-w-25">
<Chip
:color="statusColorMap[user.status]"
size="sm"
variant="soft"
>
{{ user.status }}
</Chip>
</TableCell>
<TableCell>
<div class="flex items-center gap-1">
<Button
is-icon-only
:aria-label="`查看 ${user.name}`"
size="sm"
variant="tertiary"
>
<IconEye class="size-4" aria-hidden="true" />
</Button>
<Button
is-icon-only
:aria-label="`编辑 ${user.name}`"
size="sm"
variant="tertiary"
>
<IconPencil class="size-4" aria-hidden="true" />
</Button>
<Button
is-icon-only
:aria-label="`删除 ${user.name}`"
size="sm"
variant="danger-soft"
>
<IconTrash class="size-4" aria-hidden="true" />
</Button>
</div>
</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
import {
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
const headerCell = "text-xs font-semibold uppercase tracking-wide text-muted";
const rowClass =
"border-t border-border/60 transition-colors hover:bg-default even:bg-surface-secondary";
</script>
<template>
<Table
class="w-full max-w-2xl overflow-hidden rounded-xl border border-border/80 shadow-sm"
>
<TableScrollContainer>
<TableContent aria-label="团队成员" class="min-w-[600px]">
<TableHeader class="bg-surface-secondary">
<TableColumn is-row-header :class="headerCell">姓名</TableColumn>
<TableColumn :class="headerCell">角色</TableColumn>
<TableColumn :class="headerCell">状态</TableColumn>
</TableHeader>
<TableBody>
<TableRow row-key="1" :class="rowClass">
<TableCell class="font-medium text-foreground">
Kate Moore
</TableCell>
<TableCell>CEO</TableCell>
<TableCell>在职</TableCell>
</TableRow>
<TableRow row-key="2" :class="rowClass">
<TableCell class="font-medium text-foreground">
John Smith
</TableCell>
<TableCell>CTO</TableCell>
<TableCell>在职</TableCell>
</TableRow>
<TableRow row-key="3" :class="rowClass">
<TableCell class="font-medium text-foreground">
Sara Johnson
</TableCell>
<TableCell>CMO</TableCell>
<TableCell>休假中</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>
+40
View File
@@ -0,0 +1,40 @@
<script setup lang="ts">
import { IconInbox } from "@tabler/icons-vue";
import {
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
</script>
<template>
<Table class="min-h-[200px]">
<TableScrollContainer>
<TableContent aria-label="空表格" class="h-full min-w-[600px]">
<TableHeader>
<TableColumn is-row-header>姓名</TableColumn>
<TableColumn>角色</TableColumn>
<TableColumn>状态</TableColumn>
<TableColumn>邮箱</TableColumn>
</TableHeader>
<TableBody>
<TableRow row-key="empty" :is-disabled="true">
<TableCell :colspan="4">
<div
class="flex h-full w-full flex-col items-center justify-center gap-4 py-8 text-center"
>
<IconInbox class="size-6 text-muted" aria-hidden="true" />
<span class="text-sm text-muted">未找到结果</span>
</div>
</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>
+155
View File
@@ -0,0 +1,155 @@
<script setup lang="ts">
import { ref } from "vue";
import { IconChevronRight } from "@tabler/icons-vue";
import {
Button,
Table,
type TableKey,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
type Row = {
children: Row[];
date: string;
id: string;
title: string;
type: string;
};
const data: Row[] = [
{
children: [
{
children: [
{
children: [],
date: "7/10/2025",
id: "3",
title: "周报",
type: "文件",
},
{
children: [],
date: "8/20/2025",
id: "4",
title: "预算",
type: "文件",
},
],
date: "8/2/2025",
id: "2",
title: "项目",
type: "文件夹",
},
],
date: "10/20/2025",
id: "1",
title: "文档",
type: "文件夹",
},
{
children: [
{
children: [],
date: "1/23/2026",
id: "6",
title: "图片 1",
type: "文件",
},
{
children: [],
date: "2/3/2026",
id: "7",
title: "图片 2",
type: "文件",
},
],
date: "2/3/2026",
id: "5",
title: "照片",
type: "文件夹",
},
];
const expandedKeys = ref<TableKey[]>(["1"]);
function isVisible(item: Row, depth: number, parents: string[]): boolean {
return parents.every((p) => expandedKeys.value.includes(p));
}
function renderRows(
items: Row[],
depth: number,
parents: string[],
): { item: Row; depth: number; parents: string[] }[] {
const out: { item: Row; depth: number; parents: string[] }[] = [];
for (const item of items) {
if (isVisible(item, depth, parents)) {
out.push({ item, depth, parents });
out.push(...renderRows(item.children, depth + 1, [...parents, item.id]));
}
}
return out;
}
const flatRows = () => renderRows(data, 0, []);
</script>
<template>
<Table>
<TableScrollContainer>
<TableContent
aria-label="文件"
class="min-w-[520px]"
:expanded-keys="expandedKeys"
tree-column="name"
@update:expanded-keys="(k: TableKey[]) => (expandedKeys = k)"
>
<TableHeader>
<TableColumn id="name" is-row-header>姓名</TableColumn>
<TableColumn id="type">类型</TableColumn>
<TableColumn id="date">修改日期</TableColumn>
</TableHeader>
<TableBody>
<template v-for="row in flatRows()" :key="row.item.id">
<TableRow
v-slot="{ isExpanded, toggleExpanded }"
:level="row.depth + 1"
:row-key="row.item.id"
:has-child-items="row.item.children.length > 0"
>
<TableCell>
<span
class="flex items-center gap-1"
:style="{ paddingLeft: row.depth * 16 + 'px' }"
>
<Button
v-if="row.item.children.length > 0"
is-icon-only
aria-label="切换行"
size="sm"
variant="ghost"
@click="toggleExpanded"
>
<IconChevronRight
aria-hidden="true"
class="size-4 text-muted transition-transform duration-150"
:class="isExpanded ? 'rotate-90' : ''"
/>
</Button>
<span>{{ row.item.title }}</span>
</span>
</TableCell>
<TableCell>{{ row.item.type }}</TableCell>
<TableCell>{{ row.item.date }}</TableCell>
</TableRow>
</template>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>
+164
View File
@@ -0,0 +1,164 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationNextIcon,
PaginationPrevious,
PaginationPreviousIcon,
PaginationSummary,
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableFooter,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
const columns = [
{ id: "name", name: "姓名" },
{ id: "role", name: "角色" },
{ id: "status", name: "状态" },
{ id: "email", name: "邮箱" },
];
const users = [
{
email: "kate@acme.com",
id: 1,
name: "Kate Moore",
role: "首席执行官",
status: "在职",
},
{
email: "john@acme.com",
id: 2,
name: "John Smith",
role: "首席技术官",
status: "在职",
},
{
email: "sara@acme.com",
id: 3,
name: "Sara Johnson",
role: "首席营销官",
status: "休假",
},
{
email: "michael@acme.com",
id: 4,
name: "Michael Brown",
role: "首席财务官",
status: "在职",
},
{
email: "emily@acme.com",
id: 5,
name: "Emily Davis",
role: "产品经理",
status: "未激活",
},
{
email: "davis@acme.com",
id: 6,
name: "Davis Wilson",
role: "首席设计师",
status: "在职",
},
{
email: "olivia@acme.com",
id: 7,
name: "Olivia Martinez",
role: "前端工程师",
status: "在职",
},
{
email: "james@acme.com",
id: 8,
name: "James Taylor",
role: "后端工程师",
status: "在职",
},
];
const ROWS_PER_PAGE = 4;
const page = ref(1);
const totalPages = Math.ceil(users.length / ROWS_PER_PAGE);
const pages = Array.from({ length: totalPages }, (_, i) => i + 1);
const paginatedItems = computed(() => {
const start = (page.value - 1) * ROWS_PER_PAGE;
return users.slice(start, start + ROWS_PER_PAGE);
});
const start = computed(() => (page.value - 1) * ROWS_PER_PAGE + 1);
const end = computed(() => Math.min(page.value * ROWS_PER_PAGE, users.length));
</script>
<template>
<Table>
<TableScrollContainer>
<TableContent aria-label="带分页的表格" class="min-w-[600px]">
<TableHeader>
<TableColumn
v-for="column in columns"
:key="column.id"
:id="column.id"
:is-row-header="column.id === 'name'"
>
{{ column.name }}
</TableColumn>
</TableHeader>
<TableBody>
<TableRow
v-for="user in paginatedItems"
:key="user.id"
:row-key="String(user.id)"
>
<TableCell>{{ user.name }}</TableCell>
<TableCell>{{ user.role }}</TableCell>
<TableCell>{{ user.status }}</TableCell>
<TableCell>{{ user.email }}</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
<TableFooter>
<Pagination size="sm">
<PaginationSummary>
{{ start }}–{{ end }} / 共 {{ users.length }} 条
</PaginationSummary>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
:is-disabled="page === 1"
@click="page = Math.max(1, page - 1)"
>
<PaginationPreviousIcon />
上一页
</PaginationPrevious>
</PaginationItem>
<PaginationItem v-for="p in pages" :key="p">
<PaginationLink :is-active="p === page" @click="page = p">
{{ p }}
</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationNext
:is-disabled="page === totalPages"
@click="page = Math.min(totalPages, page + 1)"
>
下一页
<PaginationNextIcon />
</PaginationNext>
</PaginationItem>
</PaginationContent>
</Pagination>
</TableFooter>
</Table>
</template>
@@ -0,0 +1,53 @@
<script setup lang="ts">
import {
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
</script>
<template>
<Table variant="secondary">
<TableScrollContainer>
<TableContent aria-label="团队成员" class="min-w-[600px]">
<TableHeader>
<TableColumn is-row-header>姓名</TableColumn>
<TableColumn>角色</TableColumn>
<TableColumn>状态</TableColumn>
<TableColumn>邮箱</TableColumn>
</TableHeader>
<TableBody>
<TableRow row-key="1">
<TableCell>Kate Moore</TableCell>
<TableCell>首席执行官</TableCell>
<TableCell>在职</TableCell>
<TableCell>kate@acme.com</TableCell>
</TableRow>
<TableRow row-key="2">
<TableCell>John Smith</TableCell>
<TableCell>首席技术官</TableCell>
<TableCell>在职</TableCell>
<TableCell>john@acme.com</TableCell>
</TableRow>
<TableRow row-key="3">
<TableCell>Sara Johnson</TableCell>
<TableCell>首席营销官</TableCell>
<TableCell>休假</TableCell>
<TableCell>sara@acme.com</TableCell>
</TableRow>
<TableRow row-key="4">
<TableCell>Michael Brown</TableCell>
<TableCell>首席财务官</TableCell>
<TableCell>在职</TableCell>
<TableCell>michael@acme.com</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>
+126
View File
@@ -0,0 +1,126 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Table,
type TableKey,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
const users = [
{
email: "kate@acme.com",
id: "1",
name: "Kate Moore",
role: "首席执行官",
status: "在职",
},
{
email: "john@acme.com",
id: "2",
name: "John Smith",
role: "首席技术官",
status: "在职",
},
{
email: "sara@acme.com",
id: "3",
name: "Sara Johnson",
role: "首席营销官",
status: "休假",
},
{
email: "michael@acme.com",
id: "4",
name: "Michael Brown",
role: "首席财务官",
status: "在职",
},
];
const selectedKeys = ref<TableKey[]>([]);
const allChecked = computed(
() => users.length > 0 && selectedKeys.value.length === users.length,
);
function toggleAll() {
selectedKeys.value = allChecked.value ? [] : users.map((u) => u.id);
}
function toggleOne(id: string) {
selectedKeys.value = selectedKeys.value.includes(id)
? selectedKeys.value.filter((k) => k !== id)
: [...selectedKeys.value, id];
}
</script>
<template>
<div class="flex flex-col gap-3">
<Table>
<TableScrollContainer>
<TableContent
aria-label="带选择的表格"
class="min-w-[600px]"
selection-mode="multiple"
:selected-keys="selectedKeys"
@update:selected-keys="(k: TableKey[]) => (selectedKeys = k)"
>
<TableHeader>
<TableColumn class="pe-0">
<Checkbox
aria-label="全选"
:is-selected="allChecked"
@update:checked="toggleAll"
>
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
</CheckboxContent>
</Checkbox>
</TableColumn>
<TableColumn is-row-header>姓名</TableColumn>
<TableColumn>角色</TableColumn>
<TableColumn>状态</TableColumn>
<TableColumn>邮箱</TableColumn>
</TableHeader>
<TableBody>
<TableRow v-for="user in users" :key="user.id" :row-key="user.id">
<TableCell class="pe-0">
<Checkbox
:aria-label="`选择 ${user.name}`"
variant="secondary"
:is-selected="selectedKeys.includes(user.id)"
@update:checked="() => toggleOne(user.id)"
>
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
</CheckboxContent>
</Checkbox>
</TableCell>
<TableCell>{{ user.name }}</TableCell>
<TableCell>{{ user.role }}</TableCell>
<TableCell>{{ user.status }}</TableCell>
<TableCell>{{ user.email }}</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
<p class="text-sm text-muted">
已选:
<span class="font-medium">
{{ selectedKeys.length > 0 ? selectedKeys.join(", ") : "无" }}
</span>
</p>
</div>
</template>
+138
View File
@@ -0,0 +1,138 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
TableSortableColumnHeader,
} from "@heroui-vue/components";
interface User {
id: number;
name: string;
role: string;
status: string;
email: string;
}
const users: User[] = [
{
email: "kate@acme.com",
id: 1,
name: "Kate Moore",
role: "首席执行官",
status: "在职",
},
{
email: "john@acme.com",
id: 2,
name: "John Smith",
role: "首席技术官",
status: "在职",
},
{
email: "sara@acme.com",
id: 3,
name: "Sara Johnson",
role: "首席营销官",
status: "休假",
},
{
email: "michael@acme.com",
id: 4,
name: "Michael Brown",
role: "首席财务官",
status: "在职",
},
{
email: "emily@acme.com",
id: 5,
name: "Emily Davis",
role: "产品经理",
status: "未激活",
},
];
const sortDescriptor = ref<{
column: string;
direction: "ascending" | "descending";
}>({
column: "name",
direction: "ascending",
});
const sortedUsers = computed(() => {
const col = sortDescriptor.value.column as keyof User;
return [...users].sort((a, b) => {
let cmp = String(a[col]).localeCompare(String(b[col]));
if (sortDescriptor.value.direction === "descending") cmp *= -1;
return cmp;
});
});
function dirOf(id: string): "ascending" | "descending" | undefined {
return sortDescriptor.value.column === id
? sortDescriptor.value.direction
: undefined;
}
function onSortChange(
d: { column: string; direction: "ascending" | "descending" | "none" } | null,
) {
if (d && d.direction !== "none") {
sortDescriptor.value = { column: d.column, direction: d.direction };
}
}
</script>
<template>
<Table>
<TableScrollContainer>
<TableContent
aria-label="可排序表格"
class="min-w-[600px]"
:sort-descriptor="sortDescriptor"
@update:sort-descriptor="onSortChange"
>
<TableHeader>
<TableColumn id="name" is-row-header allows-sorting>
<TableSortableColumnHeader :sort-direction="dirOf('name')">
姓名
</TableSortableColumnHeader>
</TableColumn>
<TableColumn id="role" allows-sorting>
<TableSortableColumnHeader :sort-direction="dirOf('role')">
角色
</TableSortableColumnHeader>
</TableColumn>
<TableColumn id="status" allows-sorting>
<TableSortableColumnHeader :sort-direction="dirOf('status')">
状态
</TableSortableColumnHeader>
</TableColumn>
<TableColumn id="email" allows-sorting>
<TableSortableColumnHeader :sort-direction="dirOf('email')">
邮箱
</TableSortableColumnHeader>
</TableColumn>
</TableHeader>
<TableBody>
<TableRow
v-for="user in sortedUsers"
:key="user.id"
:row-key="String(user.id)"
>
<TableCell>{{ user.name }}</TableCell>
<TableCell>{{ user.role }}</TableCell>
<TableCell>{{ user.status }}</TableCell>
<TableCell>{{ user.email }}</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
</Table>
</template>
+246
View File
@@ -0,0 +1,246 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Chip,
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationNextIcon,
PaginationPrevious,
PaginationPreviousIcon,
PaginationSummary,
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableFooter,
TableHeader,
TableRow,
TableScrollContainer,
TableSortableColumnHeader,
} from "@heroui-vue/components";
import {
createTable,
getCoreRowModel,
getSortedRowModel,
type SortingState,
} from "@tanstack/table-core";
interface User {
id: number;
name: string;
role: string;
status: "在职" | "未激活" | "休假";
email: string;
}
const statusColorMap: Record<string, "success" | "danger" | "warning"> = {
休假: "warning",
在职: "success",
未激活: "danger",
};
const users: User[] = [
{
email: "kate@acme.com",
id: 1,
name: "Kate Moore",
role: "首席执行官",
status: "在职",
},
{
email: "john@acme.com",
id: 2,
name: "John Smith",
role: "首席技术官",
status: "在职",
},
{
email: "sara@acme.com",
id: 3,
name: "Sara Johnson",
role: "首席营销官",
status: "休假",
},
{
email: "michael@acme.com",
id: 4,
name: "Michael Brown",
role: "首席财务官",
status: "在职",
},
{
email: "emily@acme.com",
id: 5,
name: "Emily Davis",
role: "产品经理",
status: "未激活",
},
{
email: "davis@acme.com",
id: 6,
name: "Davis Wilson",
role: "首席设计师",
status: "在职",
},
{
email: "olivia@acme.com",
id: 7,
name: "Olivia Martinez",
role: "前端工程师",
status: "在职",
},
{
email: "james@acme.com",
id: 8,
name: "James Taylor",
role: "后端工程师",
status: "在职",
},
];
// TanStack-style column model + sorting state driving the Vue table surface.
const columns = [
{ id: "name", header: "姓名" },
{ id: "role", header: "角色" },
{ id: "status", header: "状态" },
{ id: "email", header: "邮箱" },
] as const;
const sorting = ref<SortingState>([{ id: "name", desc: false }]);
const page = ref(1);
const ROWS_PER_PAGE = 4;
// Real TanStack table model: core row model + sorted row model.
const table = computed(() =>
createTable({
data: users,
columns: [
{ id: "name", accessorKey: "name" },
{ id: "role", accessorKey: "role" },
{ id: "status", accessorKey: "status" },
{ id: "email", accessorKey: "email" },
],
state: { sorting: sorting.value },
onStateChange: () => {},
renderFallbackValue: null,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
}),
);
const sortedUsers = computed(() =>
table.value.getSortedRowModel().rows.map((r) => r.original),
);
const paginatedItems = computed(() => {
const start = (page.value - 1) * ROWS_PER_PAGE;
return sortedUsers.value.slice(start, start + ROWS_PER_PAGE);
});
const totalPages = computed(() =>
Math.ceil(sortedUsers.value.length / ROWS_PER_PAGE),
);
const sortDescriptor = computed(() => {
const s = sorting.value[0];
return s
? {
column: s.id,
direction: (s.desc ? "descending" : "ascending") as
"ascending" | "descending",
}
: null;
});
function onSortChange(
d: { column: string; direction: "ascending" | "descending" | "none" } | null,
) {
if (!d || d.direction === "none") {
sorting.value = [];
return;
}
sorting.value = [{ id: d.column, desc: d.direction === "descending" }];
page.value = 1;
}
function dirOf(id: string): "ascending" | "descending" | undefined {
const s = sorting.value[0];
return s && s.id === id ? (s.desc ? "descending" : "ascending") : undefined;
}
</script>
<template>
<Table>
<TableScrollContainer>
<TableContent
aria-label="TanStack 表格"
class="min-w-[600px]"
:sort-descriptor="sortDescriptor"
@update:sort-descriptor="onSortChange"
>
<TableHeader>
<TableColumn
v-for="col in columns"
:key="col.id"
:id="col.id"
:is-row-header="col.id === 'name'"
allows-sorting
>
<TableSortableColumnHeader :sort-direction="dirOf(col.id)">
{{ col.header }}
</TableSortableColumnHeader>
</TableColumn>
</TableHeader>
<TableBody>
<TableRow
v-for="user in paginatedItems"
:key="user.id"
:row-key="String(user.id)"
>
<TableCell>{{ user.name }}</TableCell>
<TableCell>{{ user.role }}</TableCell>
<TableCell>
<Chip
:color="statusColorMap[user.status]"
size="sm"
variant="soft"
>
{{ user.status }}
</Chip>
</TableCell>
<TableCell>{{ user.email }}</TableCell>
</TableRow>
</TableBody>
</TableContent>
</TableScrollContainer>
<TableFooter>
<Pagination size="sm">
<PaginationSummary>
{{ sortedUsers.length }} 条 · 第 {{ page }} / {{ totalPages }} 页
</PaginationSummary>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
:is-disabled="page === 1"
@click="page = Math.max(1, page - 1)"
>
<PaginationPreviousIcon />
上一页
</PaginationPrevious>
</PaginationItem>
<PaginationItem>
<PaginationLink is-active>{{ page }}</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationNext
:is-disabled="page === totalPages"
@click="page = Math.min(totalPages, page + 1)"
>
下一页
<PaginationNextIcon />
</PaginationNext>
</PaginationItem>
</PaginationContent>
</Pagination>
</TableFooter>
</Table>
</template>
+184
View File
@@ -0,0 +1,184 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import {
Table,
TableBody,
TableCell,
TableColumn,
TableContent,
TableHeader,
TableRow,
TableScrollContainer,
} from "@heroui-vue/components";
interface User {
id: number;
name: string;
role: string;
email: string;
}
const roles = [
"软件工程师",
"高级工程师",
"资深工程师",
"产品经理",
"设计师",
"数据分析师",
"测试工程师",
"DevOps 工程师",
"营销经理",
"销售代表",
];
const firstNames = [
"Emma",
"Liam",
"Olivia",
"Noah",
"Ava",
"James",
"Sophia",
"Oliver",
"Isabella",
"Lucas",
"Mia",
"Ethan",
"Charlotte",
"Mason",
"Amelia",
"Logan",
"Harper",
"Alexander",
"Ella",
"Benjamin",
];
const lastNames = [
"Smith",
"Johnson",
"Williams",
"Brown",
"Jones",
"Garcia",
"Miller",
"Davis",
"Rodriguez",
"Martinez",
"Anderson",
"Taylor",
"Thomas",
"Jackson",
"White",
"Harris",
"Clark",
"Lewis",
"Robinson",
"Walker",
];
function generateUsers(count: number): User[] {
const users: User[] = [];
for (let i = 0; i < count; i++) {
const firstName = firstNames[i % firstNames.length];
const lastName =
lastNames[Math.floor(i / firstNames.length) % lastNames.length];
users.push({
email: `${firstName.toLowerCase()}.${lastName.toLowerCase()}@acme.com`,
id: i + 1,
name: `${firstName} ${lastName}`,
role: roles[i % roles.length],
});
}
return users;
}
const users = generateUsers(1000);
const ITEM_HEIGHT = 48;
const rowKeys = users.map((user) => user.id);
const VIEWPORT = 320;
const OVERSCAN = 8;
const scrollTop = ref(0);
const scrollEl = ref<HTMLElement | null>(null);
const startIndex = computed(() =>
Math.max(0, Math.floor(scrollTop.value / ITEM_HEIGHT) - OVERSCAN),
);
const endIndex = computed(() =>
Math.min(
users.length,
Math.ceil((scrollTop.value + VIEWPORT) / ITEM_HEIGHT) + OVERSCAN,
),
);
const visible = computed(() => users.slice(startIndex.value, endIndex.value));
const padTop = computed(() => startIndex.value * ITEM_HEIGHT);
const padBottom = computed(() => (users.length - endIndex.value) * ITEM_HEIGHT);
function focusRow(_key: string | number, index: number) {
const node = scrollEl.value;
if (!node) return;
const top = index * ITEM_HEIGHT;
if (top < node.scrollTop) node.scrollTop = top;
else if (top + ITEM_HEIGHT > node.scrollTop + VIEWPORT - 44)
node.scrollTop = top + ITEM_HEIGHT - VIEWPORT + 44;
scrollTop.value = node.scrollTop;
}
function onScroll(event: Event) {
scrollTop.value = (event.target as HTMLElement).scrollTop;
}
onMounted(() => {
scrollEl.value?.addEventListener("scroll", onScroll, { passive: true });
});
onUnmounted(() => {
scrollEl.value?.removeEventListener("scroll", onScroll);
});
</script>
<template>
<Table>
<div
ref="scrollEl"
class="h-[320px] w-full overflow-auto"
data-slot="table-virtual-viewport"
>
<TableContent
aria-label="虚拟化表格"
class="min-w-[600px] table-fixed"
:row-keys="rowKeys"
:aria-rowcount="users.length + 1"
@focus-row="focusRow"
>
<TableHeader aria-rowindex="1">
<TableColumn id="name" is-row-header>姓名</TableColumn>
<TableColumn id="role">角色</TableColumn>
<TableColumn id="email">邮箱</TableColumn>
</TableHeader>
<TableBody>
<tr aria-hidden="true" :style="{ height: padTop + 'px' }" />
<TableRow
v-for="user in visible"
:key="user.id"
:row-key="user.id"
:aria-rowindex="user.id + 1"
:style="{ height: ITEM_HEIGHT + 'px' }"
>
<TableCell
class="h-12 whitespace-nowrap overflow-hidden text-ellipsis"
>
{{ user.name }}
</TableCell>
<TableCell
class="h-12 whitespace-nowrap overflow-hidden text-ellipsis"
>
{{ user.role }}
</TableCell>
<TableCell
class="h-12 whitespace-nowrap overflow-hidden text-ellipsis"
>
{{ user.email }}
</TableCell>
</TableRow>
<tr aria-hidden="true" :style="{ height: padBottom + 'px' }" />
</TableBody>
</TableContent>
</div>
</Table>
</template>
+112
View File
@@ -0,0 +1,112 @@
<script setup lang="ts">
import { ref } from "vue";
import { IconCheck } from "@tabler/icons-vue";
import { onBeforeUnmount } from "vue";
import {
Button,
ToastProvider,
ToastQueue,
createToastFunction,
} from "@heroui-vue/components";
const queue = new ToastQueue();
const toast = createToastFunction(queue);
onBeforeUnmount(() => queue.destroy());
const closedHistory = ref<{ message: string; time: string }[]>([]);
function history(message: string) {
closedHistory.value = [
{ message, time: new Date().toLocaleTimeString() },
...closedHistory.value,
].slice(0, 5);
}
</script>
<template>
<div class="flex h-full max-w-2xl flex-col items-center justify-center gap-6">
<div class="flex w-full flex-wrap items-center justify-center gap-4">
<Button
size="sm"
variant="secondary"
@click="
toast('文件已保存', {
timeout: 3000,
onClose: () => history('文件已保存(3 秒后关闭)'),
})
"
>
自定义超时(3 秒)
</Button>
<Button
size="sm"
variant="secondary"
@click="
toast('更改已保存', {
timeout: 10000,
onClose: () => history('更改已保存(10 秒后关闭)'),
})
"
>
自定义超时(10 秒)
</Button>
<Button
size="sm"
variant="secondary"
@click="
toast.success('活动已创建', {
onClose: () => history('活动已创建(默认超时后关闭)'),
})
"
>
使用 onClose 回调
</Button>
<Button
size="sm"
variant="secondary"
@click="
toast('重要通知', {
description: '此 Toast 将保持显示直至关闭',
timeout: 0,
onClose: () => history('重要通知(手动关闭)'),
})
"
>
持久显示 Toast
</Button>
</div>
<div class="w-full space-y-2">
<div class="flex items-center justify-between">
<h3 class="text-sm font-medium">关闭历史</h3>
<Button
v-if="closedHistory.length"
size="sm"
variant="tertiary"
class="h-6 text-xs"
@click="closedHistory = []"
>
清空
</Button>
</div>
<div
class="min-h-[120px] space-y-2 rounded-lg border border-border bg-surface p-4"
>
<p v-if="!closedHistory.length" class="text-sm text-muted">
尚无已关闭的 Toast。请尝试关闭上方的 Toast!
</p>
<div
v-for="(item, index) in closedHistory"
:key="item.time + '-' + index"
class="flex items-start justify-between gap-3 rounded-md border border-border bg-default px-3 py-2 text-sm"
>
<div class="flex-1">
<span class="font-medium">{{ item.message }}</span>
<span class="ms-2 text-xs text-muted">({{ item.time }})</span>
</div>
<div
class="flex size-5 shrink-0 items-center justify-center rounded-full bg-success/10 text-success"
>
<IconCheck class="size-3" aria-hidden="true" />
</div>
</div>
</div>
</div>
<ToastProvider :queue="queue" to="body" />
</div>
</template>
@@ -0,0 +1,28 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import { h } from "vue";
import { IconStar } from "@tabler/icons-vue";
import {
Button,
ToastProvider,
createToastFunction,
ToastQueue,
type ToastContentValue,
} from "@heroui-vue/components";
const queue = new ToastQueue<ToastContentValue>();
onBeforeUnmount(() => queue.destroy());
const toast = createToastFunction(queue);
function show() {
toast("自定义图标指示器", {
indicator: h(IconStar, { class: "size-5", "aria-hidden": "true" }),
});
}
</script>
<template>
<div class="flex flex-col gap-3">
<Button size="sm" variant="secondary" @click="show">自定义指示器</Button>
<ToastProvider :queue="queue" to="body" />
</div>
</template>
+61
View File
@@ -0,0 +1,61 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import { Button, ToastProvider, ToastQueue } from "@heroui-vue/components";
const notificationQueue = new ToastQueue({ maxVisibleToasts: 2 });
const errorQueue = new ToastQueue({ maxVisibleToasts: 3 });
const successQueue = new ToastQueue({ maxVisibleToasts: 1 });
onBeforeUnmount(() =>
[notificationQueue, errorQueue, successQueue].forEach((queue) =>
queue.destroy(),
),
);
</script>
<template>
<div
class="flex h-full max-w-4xl flex-wrap items-center justify-center gap-4"
>
<Button
size="sm"
variant="secondary"
@click="
notificationQueue.add({
title: '新通知',
description: '您有一条新消息',
variant: 'default',
})
"
>
添加通知(最多 2 条)
</Button>
<Button
size="sm"
variant="danger-soft"
@click="
errorQueue.add({
title: '发生错误',
description: '保存更改失败',
variant: 'danger',
})
"
>
添加错误(最多 3 条)
</Button>
<Button
size="sm"
variant="secondary"
class="text-success"
@click="
successQueue.add({
title: '成功!',
description: `操作 ${Date.now()}`,
variant: 'success',
})
"
>
添加成功(最多 1 条)
</Button>
<ToastProvider :queue="notificationQueue" to="body" placement="bottom" />
<ToastProvider :queue="errorQueue" to="body" placement="bottom start" />
<ToastProvider :queue="successQueue" to="body" placement="bottom end" />
</div>
</template>
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import {
Button,
ToastContent,
ToastTitle,
ToastDescription,
ToastIndicator,
ToastProvider,
ToastQueue,
createToastFunction,
} from "@heroui-vue/components";
const queue = new ToastQueue();
const toast = createToastFunction(queue);
onBeforeUnmount(() => queue.destroy());
</script>
<template>
<div class="flex flex-col items-center gap-4">
<Button
size="sm"
variant="secondary"
@click="toast('已保存', { description: '草稿已同步' })"
>
显示提示
</Button>
<ToastProvider
:queue="queue"
toast-class="rounded-xl border border-border/80 bg-surface shadow-lg ring-1 ring-black/5 dark:ring-white/10"
to="body"
>
<template #default="{ toast: item }">
<ToastContent>
<div class="flex items-center gap-2.5">
<ToastIndicator
class="text-neutral-600 dark:text-neutral-400"
:variant="item.variant"
/>
<div class="flex flex-col gap-0.5">
<ToastTitle
class="text-sm font-medium text-neutral-900 dark:text-neutral-50"
>
{{ item.title }}
</ToastTitle>
<ToastDescription
class="text-sm text-neutral-600 dark:text-neutral-400"
>
{{ item.description }}
</ToastDescription>
</div>
</div>
</ToastContent>
</template>
</ToastProvider>
</div>
</template>
+49
View File
@@ -0,0 +1,49 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import {
Button,
ToastContent,
ToastTitle,
ToastDescription,
ToastIndicator,
ToastCloseButton,
ToastProvider,
ToastQueue,
createToastFunction,
} from "@heroui-vue/components";
const queue = new ToastQueue();
const toast = createToastFunction(queue);
onBeforeUnmount(() => queue.destroy());
</script>
<template>
<div class="flex h-full max-w-xl flex-col items-center justify-center">
<Button
size="sm"
variant="secondary"
@click="toast('自定义布局 Toast', { description: '使用自定义渲染函数' })"
>
自定义 Toast
</Button>
<ToastProvider
:queue="queue"
toast-class="rounded-xl border border-border"
to="body"
>
<template #default="{ toast: item, close }">
<ToastContent>
<div class="flex items-center gap-2">
<ToastIndicator class="text-accent" :variant="item.variant" />
<div class="flex flex-col pe-6">
<ToastTitle class="text-accent">{{ item.title }}</ToastTitle>
<ToastDescription>{{ item.description }}</ToastDescription>
</div>
</div>
</ToastContent>
<ToastCloseButton
class="absolute end-2 top-1/2 -translate-y-1/2 border-none bg-transparent opacity-100 [&>svg]:size-4"
@click="close"
/>
</template>
</ToastProvider>
</div>
</template>
+30
View File
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import {
Button,
ToastProvider,
createToastFunction,
ToastQueue,
type ToastContentValue,
} from "@heroui-vue/components";
import { h } from "vue";
import { IconUsers } from "@tabler/icons-vue";
const queue = new ToastQueue<ToastContentValue>();
onBeforeUnmount(() => queue.destroy());
const toast = createToastFunction(queue);
function show() {
toast("您已被邀请加入团队", {
description: "Bob 邀请您加入 HeroUI 团队",
indicator: h(IconUsers),
actionProps: { label: "忽略", variant: "tertiary" },
});
}
</script>
<template>
<div class="flex h-full max-w-xl flex-col items-center justify-center">
<Button size="sm" variant="secondary" @click="show">显示 Toast</Button>
<ToastProvider :queue="queue" to="body" />
</div>
</template>
+38
View File
@@ -0,0 +1,38 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import {
Button,
ToastProvider,
ToastQueue,
createToastFunction,
} from "@heroui-vue/components";
const queue = new ToastQueue();
const toast = createToastFunction(queue);
onBeforeUnmount(() => queue.destroy());
const timers = new Set<ReturnType<typeof setTimeout>>();
onBeforeUnmount(() => timers.forEach(clearTimeout));
function show() {
toast("简单消息");
for (const [delay, run] of [
[400, () => toast.success("操作已完成")],
[800, () => toast.info("有新更新可用")],
] as const) {
const timer = setTimeout(() => {
timers.delete(timer);
run();
}, delay);
timers.add(timer);
}
}
</script>
<template>
<div class="flex h-full max-w-xl flex-col items-center justify-center">
<Button size="sm" variant="secondary" @click="show">显示 3 条 Toast</Button>
<ToastProvider
:queue="queue"
is-expanded
aria-label="展开的通知"
to="body"
/>
</div>
</template>
+47
View File
@@ -0,0 +1,47 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import {
Button,
ToastProvider,
createToastFunction,
ToastQueue,
type ToastContentValue,
} from "@heroui-vue/components";
const placements = [
"top start",
"top",
"top end",
"bottom start",
"bottom",
"bottom end",
] as const;
// One queue + provider per placement so the toast is actually mounted
// into that corner of the viewport.
const instances = placements.map((placement) => {
const queue = new ToastQueue<ToastContentValue>({ maxVisibleToasts: 2 });
return { placement, queue, toast: createToastFunction(queue) };
});
onBeforeUnmount(() =>
instances.forEach((instance) => instance.queue.destroy()),
);
</script>
<template>
<div class="flex flex-wrap gap-3">
<template v-for="inst in instances" :key="inst.placement">
<Button
variant="secondary"
@click="inst.toast(`位置:${inst.placement}`, { timeout: 3000 })"
>
{{ inst.placement }}
</Button>
<ToastProvider
:queue="inst.queue"
:placement="inst.placement"
to="body"
/>
</template>
</div>
</template>
+139
View File
@@ -0,0 +1,139 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import {
Button,
ToastProvider,
ToastQueue,
createToastFunction,
} from "@heroui-vue/components";
const queue = new ToastQueue();
const toast = createToastFunction(queue);
const timers = new Set<ReturnType<typeof setTimeout>>();
function later(run: () => void, delay = 2000) {
const timer = setTimeout(() => {
timers.delete(timer);
run();
}, delay);
timers.add(timer);
}
onBeforeUnmount(() => {
timers.forEach(clearTimeout);
queue.destroy();
});
function upload() {
toast.promise(
new Promise<{ filename: string; size: number }>((resolve) =>
later(() => resolve({ filename: "document.pdf", size: 1024 })),
),
{
loading: "正在上传文件…",
success: (data) => `文件 ${data.filename} 已上传(${data.size}KB)`,
error: "上传文件失败",
},
);
}
function createEvent() {
toast.promise(
new Promise<never>((_, reject) =>
later(() => reject(new Error("网络错误,请重试。"))),
),
{
loading: "正在创建活动…",
success: "活动已创建",
error: (err) => err.message,
},
);
}
function save() {
toast.promise(
new Promise<{ count: number }>((resolve, reject) =>
later(() =>
Math.random() > 0.5
? resolve({ count: 42 })
: reject(new Error("保存数据失败")),
),
),
{
loading: "正在保存更改…",
success: (data) => `已保存 ${data.count} 项`,
error: (err) => err.message,
},
);
}
function fetchUser() {
toast.promise(
new Promise<{ name: string; email: string }>((resolve) =>
later(() => resolve({ name: "John Doe", email: "john@example.com" })),
),
{
loading: "正在加载用户…",
success: (data) => `欢迎回来,${data.name}!`,
error: "获取用户失败",
},
);
}
function manual(kind: "upload" | "payment" | "error") {
const messages = {
upload: ["正在上传文件…", "文件已上传", "您的文件已成功上传", 3000],
payment: ["正在处理付款…", "付款已处理", "您的付款已成功处理", 2500],
error: ["正在保存更改…", "保存失败", "请重试", 2000],
} as const;
const [loading, title, description, delay] = messages[kind];
const id = toast(loading, {
isLoading: true,
timeout: 0,
description: kind === "upload" ? "请稍候,正在上传您的文件" : undefined,
});
later(() => {
if (
queue.visibleToasts.some((item) => item.key === id) &&
!queue.getExitingKeys().has(id)
)
toast.update(id, title, {
description,
variant: kind === "error" ? "danger" : "success",
timeout: 4000,
});
}, delay);
}
</script>
<template>
<div class="flex h-full max-w-2xl flex-col items-center justify-center gap-8">
<div class="w-full space-y-3">
<div class="text-center">
<h3 class="text-sm font-medium">使用 toast.promise()</h3>
<p class="text-xs text-muted">自动处理加载、成功和错误状态</p>
</div>
<div class="flex w-full flex-wrap items-center justify-center gap-4">
<Button size="sm" variant="secondary" @click="upload">上传文件</Button>
<Button size="sm" variant="secondary" @click="createEvent">
创建活动(错误)
</Button>
<Button size="sm" variant="secondary" @click="save">
保存数据(随机)
</Button>
<Button size="sm" variant="secondary" @click="fetchUser">
获取用户
</Button>
</div>
</div>
<div class="w-full space-y-3">
<div class="text-center">
<h3 class="text-sm font-medium">手动加载状态</h3>
<p class="text-xs text-muted">使用 isLoading 属性手动控制加载状态</p>
</div>
<div class="flex w-full flex-wrap items-center justify-center gap-4">
<Button size="sm" variant="secondary" @click="manual('upload')">
上传(含加载)
</Button>
<Button size="sm" variant="secondary" @click="manual('payment')">
付款处理
</Button>
<Button size="sm" variant="secondary" @click="manual('error')">
加载后显示错误
</Button>
</div>
</div>
<ToastProvider :queue="queue" to="body" />
</div>
</template>
+36
View File
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { onBeforeUnmount } from "vue";
import {
Button,
ToastProvider,
ToastQueue,
createToastFunction,
} from "@heroui-vue/components";
const queue = new ToastQueue();
const toast = createToastFunction(queue);
onBeforeUnmount(() => queue.destroy());
</script>
<template>
<div class="flex h-full max-w-xl flex-wrap items-center justify-center gap-4">
<Button size="sm" variant="secondary" @click="toast('简单消息')">
默认
</Button>
<Button size="sm" variant="secondary" @click="toast.success('操作已完成')">
成功
</Button>
<Button size="sm" variant="secondary" @click="toast.info('有新更新可用')">
信息
</Button>
<Button
size="sm"
variant="secondary"
@click="toast.warning('请检查您的设置')"
>
警告
</Button>
<Button size="sm" variant="secondary" @click="toast.danger('出了点问题')">
错误
</Button>
<ToastProvider :queue="queue" to="body" />
</div>
</template>
+103
View File
@@ -0,0 +1,103 @@
<script setup lang="ts">
import { h, onBeforeUnmount } from "vue";
import {
Button,
ToastProvider,
createToastFunction,
ToastQueue,
type ToastContentValue,
} from "@heroui-vue/components";
const queue = new ToastQueue<ToastContentValue>();
onBeforeUnmount(() => queue.destroy());
const toast = createToastFunction(queue);
import { IconUsers, IconDatabase } from "@tabler/icons-vue";
const variants = [
{ key: "default", label: "默认 Toast" },
{ key: "accent", label: "强调 Toast" },
{ key: "success", label: "成功 Toast" },
{ key: "warning", label: "警告 Toast" },
{ key: "danger", label: "危险 Toast" },
] as const;
function show(v: (typeof variants)[number]["key"]) {
const messages = {
default: {
title: "您已被邀请加入团队",
description: "Bob 邀请您加入 HeroUI 团队",
action: "忽略",
},
accent: {
title: "您还剩 2 个积分",
description: "升级付费方案以获取更多积分",
action: "升级",
},
success: {
title: "您已升级方案",
description: "您可以继续使用 HeroUI Chat",
action: "账单",
},
warning: {
title: "您的积分已用完",
description: "升级付费方案以继续使用",
action: "升级",
},
danger: {
title: "存储空间已满",
description:
"删除文件以释放空间。此处增加更多文字以演示较长内容的显示效果",
action: "删除",
},
};
const item = messages[v];
toast(item.title, {
variant: v,
description: item.description,
indicator:
v === "default"
? h(IconUsers)
: v === "danger"
? h(IconDatabase)
: undefined,
actionProps: {
label: item.action,
variant:
v === "danger" ? "danger" : v === "default" ? "tertiary" : "secondary",
class:
v === "success"
? "bg-success text-success-foreground"
: v === "warning"
? "bg-warning text-warning-foreground"
: undefined,
},
});
}
</script>
<template>
<div class="flex flex-wrap gap-3">
<Button
v-for="v in variants"
:key="v.key"
size="sm"
:variant="
v.key === 'danger'
? 'danger-soft'
: v.key === 'accent'
? 'secondary'
: 'tertiary'
"
:class="
v.key === 'success'
? 'text-success'
: v.key === 'warning'
? 'text-warning'
: undefined
"
@click="show(v.key)"
>
{{ v.label }}
</Button>
<ToastProvider :queue="queue" to="body" />
</div>
</template>
+2 -1
View File
@@ -9,7 +9,8 @@
"devDependencies": {
"@tailwindcss/vite": "^4.1.0",
"tailwindcss": "^4.1.0",
"vitepress": "^1.6.4"
"vitepress": "^1.6.4",
"@tanstack/table-core": "^8.21.3"
},
"dependencies": {
"@heroui-vue/components": "workspace:*",