useAiConversations 会话历史管理 💾
管理侧边栏会话列表的专用 Hook,特性:
- 📁 可插拔持久化(localStorage / IndexedDB / 自定义适配器)
- 🗂️ 按时间自动分组(今天 / 最近 7 天 / 最近 30 天 / 更早)
- 📌 置顶操作
- ♾️ 分页懒加载
- 🌐 SSR 友好(
readyPromise 等待初始化)
基础用法(带分组 + 置顶 + CRUD)
实时演示会话列表的完整交互:按时间分组、新建、删除、置顶。
IndexedDB 模式(大量数据 + 分页懒加载)
使用 IndexedDBAdapter 适配器,支持超大量历史记录,分页懒加载按需获取。
持久化适配器对比
| 模式 | 场景 | 容量 | SSR 兼容 |
|---|---|---|---|
storage: false | 纯内存,不持久化 | 无限制 | ✅ |
storage: 'localStorage'(默认) | 少量历史 | ~5MB | ✅(自动跳过) |
storage: 'indexedDB' | 大量历史 + 富数据 | 无上限 | ✅(async init) |
storage: CustomAdapter | 自定义后端接口 | — | ✅ |
自定义适配器(对接后端 API)
ts
import { useAiConversations, type StorageAdapter } from '@yh-ui/hooks'
const apiAdapter: StorageAdapter = {
getItem: async (key) => {
const res = await fetch(`/api/user/conversations?key=${key}`)
return res.ok ? res.text() : null
},
setItem: async (key, value) => {
await fetch('/api/user/conversations', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key, value })
})
},
removeItem: async (key) => {
await fetch(`/api/user/conversations?key=${key}`, { method: 'DELETE' })
}
}
const { conversations } = useAiConversations({ storage: apiAdapter })API
Options
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
initialConversations | AiConversation[] | [] | 初始数据(SSR 直出) |
idGenerator | () => string | 随机字符串 | 自定义 ID 生成 |
storage | false | 'localStorage' | 'indexedDB' | StorageAdapter | 'localStorage' | 持久化适配器 |
storageKey | string | 'yh-ui-ai-conversations' | 存储 key |
pageSize | number | 20 | 每页加载数 |
返回值
| 字段 | 类型 | 说明 |
|---|---|---|
conversations | Ref<AiConversation[]> | 完整会话列表 |
groupedConversations | Computed<ConversationGroup[]> | 按时间分组后的列表 |
pagedConversations | Computed<AiConversation[]> | 当前分页数据 |
hasMore | Computed<boolean> | 是否还有更多 |
loadMore | () => Promise<void> | 加载下一页 |
isLoadingMore | Ref<boolean> | 加载中状态 |
ready | Promise<void> | 初始化完成(SSR await) |
createConversation | (title, meta?) => Promise<AiConversation> | 新建会话 |
removeConversation | (id) => Promise<void> | 删除会话 |
updateConversation | (id, updates) => Promise<void> | 更新会话 |
pinConversation | (id, pinned?) => Promise<void> | 置顶/取消 |
clear | () => Promise<void> | 清空所有 |