useAiConversations 会话历史管理 💾
管理侧边栏会话列表的专用 Hook,特性:
- 📁 可插拔持久化(localStorage / IndexedDB / 自定义适配器)
- 🗂️ 按时间自动分组(今天 / 最近 7 天 / 最近 30 天 / 更早)
- 📌 置顶操作
- ♾️ 分页懒加载
- 🌐 SSR 友好(
readyPromise 等待初始化)
基础用法(带分组 + 置顶 + CRUD)
实时演示会话列表的完整交互:按时间分组、新建、删除、置顶。
IndexedDB 模式(大量数据 + 分页懒加载)
使用 storage: 'indexedDB' 配合 pagedConversations,支持大体量历史记录按页懒加载。
持久化适配器对比
| 模式 | 场景 | 容量 | 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> | 清空所有 |
远程同步
支持与后端 API 同步,实现多端数据一致性。
ts
import { useAiConversations } from '@yh-ui/hooks'
// 定义远程同步适配器
const remoteSyncAdapter = {
async fetchConversations() {
const res = await fetch('/api/conversations')
return res.json()
},
async createConversation(conv) {
const res = await fetch('/api/conversations', {
method: 'POST',
body: JSON.stringify(conv)
})
return res.json()
},
async updateConversation(id, updates) {
const res = await fetch(`/api/conversations/${id}`, {
method: 'PATCH',
body: JSON.stringify(updates)
})
return res.json()
},
async deleteConversation(id) {
await fetch(`/api/conversations/${id}`, { method: 'DELETE' })
},
async batchUpdate(conversations) {
const res = await fetch('/api/conversations/batch', {
method: 'PUT',
body: JSON.stringify(conversations)
})
return res.json()
}
}
const { conversations, isSyncing, syncError, syncToRemote, fetchFromRemote, startSync, stopSync } =
useAiConversations({
storage: 'localStorage',
remoteSync: remoteSyncAdapter,
autoSync: true,
syncInterval: 30000 // 30 秒同步一次
})远程同步 Options 扩展
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
remoteSync | RemoteSyncAdapter | - | 远程同步适配器 |
autoSync | boolean | false | 是否自动同步 |
syncInterval | number | 30000 | 同步间隔(毫秒) |
远程同步返回值
| 字段 | 类型 | 说明 | | ----------------- | --------------------- | -------------- | -------- | | isSyncing | Ref<boolean> | 同步中状态 | | lastSyncTime | Ref<number> | 上次同步时间戳 | | syncError | Ref<Error | null> | 同步错误 | | syncToRemote | () => Promise<void> | 手动同步到远程 | | fetchFromRemote | () => Promise<void> | 从远程拉取 | | startSync | () => void | 启动定时同步 | | stopSync | () => void | 停止定时同步 |
远程同步注意事项
- autoSync 和 syncInterval 仅在设置了 remoteSync 时有效
- 同步是增量的,本地新建的数据会合并到列表,不会覆盖远程已有数据
- 建议在页面卸载时调用 stopSync 停止定时同步