一句话:需要比 localStorage 更大、更可靠的离线缓存时,用 localForage——API 像 localStorage,底层自动选 IndexedDB。

写在前面

表单模板、字段树、历史记录等数据体积大、结构复杂,放 localStorage 容易触顶(约 5MB)且同步 API 会阻塞主线程。localForage 提供 Promise 化的 getItem / setItem,底层优先 IndexedDB,降级 WebSQL / localStorage。

读完你能:安装配置、创建多实例仓库、在 Vue 项目中挂载全局实例。

核心内容

1. 安装

npm install localforage

2. 基础用法

import localforage from 'localforage'

await localforage.setItem('key', { list: [1, 2, 3] }) const data = await localforage.getItem('key')

// 或 Promise 链 localforage.getItem('key').then(res => console.log(res))

支持存 对象、数组、Blob 等,无需手动 JSON.stringify(内部序列化)。

3. 创建多个实例仓库

不同业务隔离存储,避免 key 冲突:

import localforage from 'localforage'

const metaTemplateListDb = localforage.createInstance({ name: 'metaTemplateListDb', storeName: 'metaDataDbStore' })

const treeTemplateListDb = localforage.createInstance({ name: 'treeTemplateListDb', storeName: 'treeDataDbStore' })

const historyRecordDb = localforage.createInstance({ name: 'historyRecordDb', storeName: 'historyRecordDbStore' })

参数 含义
name 数据库名(IndexedDB database)
storeName 对象仓库名(object store)

4. 在 Vue 2 工程中挂载

import Vue from 'vue'
import localforage from 'localforage'

Vue.prototype.$metaTemplateListDb = localforage.createInstance({ name: 'metaTemplateListDb', storeName: 'metaDataDbStore' })

组件内:

async getDetailTemplateHandle() {
  await this.$metaTemplateListDb.setItem('template_001', { fields: [] })
  const res = await this.$metaTemplateListDb.getItem('template_001')
}

5. 常用 API

await store.setItem(key, value)
await store.getItem(key)        // 不存在返回 null
await store.removeItem(key)
await store.clear()             // 清空当前 instance
await store.keys()              // 所有 key
await store.length()            // 条目数
await store.iterate((value, key) => { /* ... */ })

6. 驱动选型(可选)

localforage.config({
  driver: [localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE],
  name: 'myApp',
  storeName: 'defaultStore'
})

默认按优先级自动降级;一般无需改。

踩坑

  1. 私有模式 / 无痕窗口 IndexedDB 可能不可用或配额极小,需 catch 并降级。
  2. Safari 旧版 IndexedDB 有 bug,关键数据要有服务端同步。
  3. 同域多 Tab 同时写同一 key 可能竞态,重要写入加版本号或锁。
  4. 存 Blob 大文件 仍受磁盘配额限制,超大文件应用分片 + 服务端。
  5. Vue 3 / Nuxt 更推荐 Pinia persist 插件@vueuse/coreuseStorage,但 localForage 适合 >5MB 结构化缓存

小结

  • localForage = localStorage 体验 + IndexedDB 容量 + 异步不阻塞。
  • 多业务用 createInstance 分库分表。
  • API 全 Promise,配合 async/await 即可。
  • 敏感数据勿只放前端,缓存仅为加速与离线兜底。

延伸阅读