Skip to content

useAiConversations 会话历史管理 💾

管理侧边栏会话列表的专用 Hook,特性:

  • 📁 可插拔持久化(localStorage / IndexedDB / 自定义适配器)
  • 🗂️ 按时间自动分组(今天 / 最近 7 天 / 最近 30 天 / 更早)
  • 📌 置顶操作
  • ♾️ 分页懒加载
  • 🌐 SSR 友好ready Promise 等待初始化)

基础用法(带分组 + 置顶 + CRUD)

实时演示会话列表的完整交互:按时间分组、新建、删除、置顶。

会话历史
今天
Vue 3 组件开发指南
如何优化 Web 性能
最近 7 天
TypeScript 高级技巧
Pinia 最佳实践
最近 30 天
Vite 插件开发入门
更早
微前端架构设计
Vue 3 组件开发指南
更新于:3/3/2026, 2:23:11 AM
如何封装高复用的组件...
分组情况:今天(2) · 最近 7 天(2) · 最近 30 天(1) · 更早(1)

IndexedDB 模式(大量数据 + 分页懒加载)

使用 IndexedDBAdapter 适配器,支持超大量历史记录,分页懒加载按需获取。

📦 IndexedDB 会话列表已加载 0 / 50 条

持久化适配器对比

模式场景容量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

参数类型默认值说明
initialConversationsAiConversation[][]初始数据(SSR 直出)
idGenerator() => string随机字符串自定义 ID 生成
storagefalse | 'localStorage' | 'indexedDB' | StorageAdapter'localStorage'持久化适配器
storageKeystring'yh-ui-ai-conversations'存储 key
pageSizenumber20每页加载数

返回值

字段类型说明
conversationsRef<AiConversation[]>完整会话列表
groupedConversationsComputed<ConversationGroup[]>按时间分组后的列表
pagedConversationsComputed<AiConversation[]>当前分页数据
hasMoreComputed<boolean>是否还有更多
loadMore() => Promise<void>加载下一页
isLoadingMoreRef<boolean>加载中状态
readyPromise<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>清空所有

Released under the MIT License.