一句话:需要比 localStorage 更大、更可靠的离线缓存时,用 localForage——API 像 localStorage,底层自动选 IndexedDB。
表单模板、字段树、历史记录等数据体积大、结构复杂,放 localStorage 容易触顶(约 5MB)且同步 API 会阻塞主线程。localForage 提供 Promise 化的 getItem / setItem,底层优先 IndexedDB,降级 WebSQL / localStorage。
读完你能:安装配置、创建多实例仓库、在 Vue 项目中挂载全局实例。
npm install localforage
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(内部序列化)。
不同业务隔离存储,避免 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) |
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')
}
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) => { /* ... */ })
localforage.config({
driver: [localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE],
name: 'myApp',
storeName: 'defaultStore'
})
默认按优先级自动降级;一般无需改。
@vueuse/core 的 useStorage,但 localForage 适合 >5MB 结构化缓存。createInstance 分库分表。async/await 即可。