Skip to content

useAiConversations 会话历史管理 💾

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

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

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

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

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

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

使用 storage: 'indexedDB' 配合 pagedConversations,支持大体量历史记录按页懒加载。

📦 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>清空所有

远程同步

支持与后端 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 扩展

参数类型默认值说明
remoteSyncRemoteSyncAdapter-远程同步适配器
autoSyncbooleanfalse是否自动同步
syncIntervalnumber30000同步间隔(毫秒)

远程同步返回值

| 字段 | 类型 | 说明 | | ----------------- | --------------------- | -------------- | -------- | | isSyncing | Ref<boolean> | 同步中状态 | | lastSyncTime | Ref<number> | 上次同步时间戳 | | syncError | Ref<Error | null> | 同步错误 | | syncToRemote | () => Promise<void> | 手动同步到远程 | | fetchFromRemote | () => Promise<void> | 从远程拉取 | | startSync | () => void | 启动定时同步 | | stopSync | () => void | 停止定时同步 |

远程同步注意事项

  1. autoSyncsyncInterval 仅在设置了 remoteSync 时有效
  2. 同步是增量的,本地新建的数据会合并到列表,不会覆盖远程已有数据
  3. 建议在页面卸载时调用 stopSync 停止定时同步

Released under the MIT License.