Skip to content

useStorageAsync

具有异步支持的反应式存储。

¥Reactive Storage in with async support.

用法

¥Usage

基本用法请参考 useStorage

¥The basic usage please refer to useStorage.

等待首次加载

¥Wait First Loaded

当用户进入你的应用时,useStorageAsync() 将从异步存储中开始加载值,有时你可能会获得默认的初始值,而不是最初存储在存储中的实际值。

¥When user entering your app, useStorageAsync() will start loading value from an async storage, sometimes you may get the default initial value, not the real value stored in storage at the very beginning.

ts
import { 
useStorageAsync
} from '@vueuse/core'
const
accessToken
=
useStorageAsync
('access.token', '', SomeAsyncStorage)
// accessToken.value may be empty before the async storage is ready
console
.
log
(
accessToken
.
value
) // ""
setTimeout
(() => {
// After some time, the async storage is ready
console
.
log
(
accessToken
.
value
) // "the real value stored in storage"
}, 500)

在这种情况下,你可以等待存储准备好,返回的值也是一个 Promise,因此你可以在模板或脚本中等待它解析。

¥In this case, you can wait the storage prepared, the returned value is also a Promise, so you can wait it resolved in your template or script.

ts
// Use top-level await if your environment supports it
const 
accessToken
= await useStorageAsync('access.token', '', SomeAsyncStorage)
console
.
log
(
accessToken
.value) // "the real value stored in storage"

如果你必须等待多个存储,请将它们放入 Promise.allSettled() 中。

¥If you must wait multiple storages, put them into a Promise.allSettled()

ts
router.onReady(async () => {
  await 
Promise
.
allSettled
([
accessToken, refreshToken, userData, ]) app.mount('app') })

选项中有一个名为 onReady 的回调:

¥There is a callback named onReady in options:

ts
import { 
useStorageAsync
} from '@vueuse/core'
// Use ES2024 Promise.withResolvers, you may use any Deferred object or EventBus to do same thing. const {
promise
,
resolve
} =
Promise
.
withResolvers
()
const
accessToken
=
useStorageAsync
('access.token', '', SomeAsyncStorage, {
onReady
(
value
) {
resolve
(
value
)
} }) // At main.ts router.onReady(async () => { // Let's wait accessToken loaded await
promise
// Now accessToken has loaded, we can safely mount our app app.mount('app') })

简单地将 resolve 用作回调:

¥Simply use resolve as callback:

ts
const 
accessToken
= useStorageAsync('access.token', '', SomeAsyncStorage, {
onReady
: resolve
})