Skip to content

useIDBKeyval ​

类别
导出体积
672 B
依赖包
@vueuse/integrations
上次更改
3 months ago

idb-keyval 的封装。

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

跨标签页同步 ​

Changes are automatically synced across browser tabs using the BroadcastChannel API. This is enabled by default and can be disabled via the listenToStorageChanges option.

ts
// disable cross-tab syncing
const { 
data
} = useIDBKeyval('my-key', 'default', {
listenToStorageChanges
: false })
js
'use strict'
// disable cross-tab syncing
const { data } = useIDBKeyval('my-key', 'default', {
  listenToStorageChanges: false,
})

类型声明 ​

显示类型声明
ts
interface 
Serializer
<
T
> {
read
: (
raw
: unknown) =>
T
write
: (
value
:
T
) => unknown
} export interface
UseIDBOptions
<
T
>
extends ConfigurableFlush, ConfigurableWindow { /** * 监听深层变化 * * @default true */
deep
?: boolean
/** * 错误回调函数 * * 默认将错误记录到 `console.error` */
onError
?: (
error
: unknown) => void
/** * 使用浅层 Ref 作为参考 * * @default false */
shallow
?: boolean
/** * 当存储中不存在时,将默认值写入存储 * * @default true */
writeDefaults
?: boolean
/** * Custom data serialization */
serializer
?:
Serializer
<
T
>
/** * Listen to storage changes from other tabs via BroadcastChannel, * useful for multiple tabs applications * * @default true */
listenToStorageChanges
?: boolean
} export interface
UseIDBKeyvalReturn
<
T
> {
data
:
RemovableRef
<
T
>
isFinished
:
ShallowRef
<boolean>
isSupported
:
ComputedRef
<boolean>
set
: (
value
:
T
) =>
Promise
<void>
} /** * * @param key * @param initialValue * @param options */ export declare function
useIDBKeyval
<
T
>(
key
:
IDBValidKey
,
initialValue
:
MaybeRefOrGetter
<
T
>,
options
?:
UseIDBOptions
<
T
>,
):
UseIDBKeyvalReturn
<
T
>

源码 ​

源码 • 演示 • 文档

贡献者 ​

一纸忘忧
Anthony Fu
IlyaL
Anthony Fu
zhcndoc-bot
👑 Edward Sammut Alessi
NoiseFan
IlyaL
Matthew
Robin
OrbisK
Fernando Fernández
Oleksandr Hyriavets
Doctorwu
Abdallah Alhaddad
Jimmy Sullivan
sun0day
Harmony Scarlet

更新日志 ​

ee4ec - feat!: sync changes across tabs (#5338)
bb831 - feat: add options.serializer (#4781)
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
1b67d - fix: use toRaw instead of overriding the original object (#3805)