$cache
A utility toolkit for interacting with IndexedDB for persistent, client-side storage.
Initialization
This module uses idb under the hood and creates an IndexedDB store named "$cache" with a single object store called "cache".
const db = await openDB("$cache", 1, {
upgrade(db) {
if (!db.objectStoreNames.contains("cache")) {
db.createObjectStore("cache")
}
},
})API
set(key: string, value: any)
Stores a value under the specified key in the cache. Triggers listeners in CacheListeners.check().
await $cache.set("user-profile", { name: "Cody" })get<T>(key: string): Promise<T | undefined>
Retrieves a value by key.
const user = await $cache.get<User>("user-profile")has(key: string): Promise<boolean>
Returns true if the key exists in the cache.
if (await $cache.has("auth-token")) {
// token exists
}delete(key: string): Promise<void>
Deletes a key from the cache.
await $cache.delete("user-settings")clear(): Promise<void>
Clears all keys and values from the cache.
await $cache.clear()keys(): Promise<string[]>
Returns all keys currently stored in the cache.
const allKeys = await $cache.keys()values<T>(): Promise<T[]>
Returns all values currently stored.
const users = await $cache.values<User>()entries<T>(): Promise<[string, T][]>
Returns all key-value pairs.
const pairs = await $cache.entries<User>()size(): Promise<number>
Returns the number of items in the cache.
const count = await $cache.size()uncache(key: string, ref: Ref<any>)
Mounts a value from cache into a Vue ref. If no value is found, sets it to null.
const profile = ref(null)
await $cache.uncache("user-profile", profile)bus
A named event bus ("$cache") used for reactive state or cross-component communication.
$cache.bus.on("update", () => { ... })
$cache.bus.emit("update")Notes
- Always use
awaitwhen calling$cachemethods. - All operations are async and safe to use in Nuxt lifecycle hooks or composables.
- IndexedDB has ~50MB quota in most modern browsers.
Example
await $cache.set("theme", "dark")
const theme = await $cache.get("theme")Related
$bus– Emits and listens to named events for this cache namespace.