Skip to content

useIDBKeyval

Category
Export Size
525 B
Package
@vueuse/integrations
Last Changed
2 months ago

idb-keyval 的封装。

Demo

Loading demo...
Available in the @vueuse/integrations add-on.

将 idb-keyval 安装为对等依赖项

bash
npm install idb-keyval@^6

使用方法

ts
import { useIDBKeyval } from '@vueuse/integrations/useIDBKeyval'

// 绑定对象
const { data: storedObject, isFinished } = useIDBKeyval('my-idb-keyval-store', { hello: 'hi', greeting: 'Hello' })

// 更新对象
storedObject.value.hello = 'hola'

// 绑定布尔值
const flag = useIDBKeyval('my-flag', true) // 返回 Ref<boolean>

// 绑定数字
const count = useIDBKeyval('my-count', 0) // 返回 Ref<number>

// 等待 IDB 事务
await count.set(10)
console.log('IDB 事务完成!')

// 从 IDB 存储中删除数据
storedObject.value = null

Type Declarations

typescript
export interface UseIDBOptions extends ConfigurableFlush {
  /**
   * Watch for deep changes
   *
   * @default true
   */
  deep?: boolean
  /**
   * On error callback
   *
   * Default log error to `console.error`
   */
  onError?: (error: unknown) => void
  /**
   * Use shallow ref as reference
   *
   * @default false
   */
  shallow?: boolean
  /**
   * Write the default value to the storage when it does not exist
   *
   * @default true
   */
  writeDefaults?: boolean
}
export interface UseIDBKeyvalReturn<T> {
  data: RemovableRef<T>
  isFinished: ShallowRef<boolean>
  set: (value: T) => Promise<void>
}
/**
 *
 * @param key
 * @param initialValue
 * @param options
 */
export declare function useIDBKeyval<T>(
  key: IDBValidKey,
  initialValue: MaybeRefOrGetter<T>,
  options?: UseIDBOptions,
): UseIDBKeyvalReturn<T>

Source

SourceDemoDocs

Contributors

Anthony Fu
丶远方
IlyaL
Anthony Fu
OrbisK
Fernando Fernández
Oleksandr Hyriavets
Doctorwu
Abdallah Alhaddad
Jimmy Sullivan
sun0day
Harmony Scarlet

Changelog

v12.8.0 on
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
v12.3.0 on
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.9.0 on
1b67d - fix: use toRaw instead of overriding the original object (#3805)
v10.8.0 on
a086e - fix: stricter types
v10.4.0 on
77a86 - feat(useIdbKeyval): ability to wait for IDB writes (#3338)
v10.0.0-beta.4 on
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue

Released under the MIT License.