Skip to content

useIDBKeyval ​

类别
导出大小
436 B
包
@vueuse/integrations
最近修改
7 months ago

idb-keyval 的封装器。

🌐 Wrapper for idb-keyval.

示例 ​

Available in the @vueuse/integrations add-on.

安装 idb-keyval 作为对等依赖 ​

🌐 Install idb-keyval as a peer dependency

bash
npm install idb-keyval@^6

用法 ​

🌐 Usage

ts
import { 
useIDBKeyval
} from '@vueuse/integrations/useIDBKeyval'
// bind object const {
data
:
storedObject
,
isFinished
} =
useIDBKeyval
('my-idb-keyval-store', {
hello
: 'hi',
greeting
: 'Hello' })
// update object
storedObject
.
value
.
hello
= 'hola'
// bind boolean const
flag
=
useIDBKeyval
('my-flag', true) // returns Ref<boolean>
// bind number const
count
=
useIDBKeyval
('my-count', 0) // returns Ref<number>
// awaiting IDB transaction await
count
.
set
(10)
console
.
log
('IDB transaction finished!')
// delete data from idb storage
storedObject
.
value
= null

跨标签同步 ​

🌐 Cross-tab syncing

通过 BroadcastChannel API,更改会自动在浏览器标签页之间同步。这个功能默认是开启的,也可以通过 listenToStorageChanges 选项关闭。

🌐 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,
})