Skip to content

useAsyncState

类别
导出体积
974 B
上次更改
3 months ago

响应式异步状态。不会阻塞你的设置函数,并且在 promise 准备就绪后会触发更改。状态默认为 shallowRef

示例

Ready: false
Loading: true
{}

用法

ts
import { 
useAsyncState
} from '@vueuse/core'
import
axios
from 'axios'
const {
state
,
isReady
,
isLoading
,
error
} =
useAsyncState
(
axios
.
get
('https://jsonplaceholder.typicode.com/todos/1')
.
then
(
t
=>
t
.
data
),
{
id
: null },
)

返回值

属性说明
state异步函数的结果
isReady当 promise 至少已解析一次时为 true
isLoading当 promise 正在等待时为 true
error如果 promise 被拒绝则为错误信息
execute重新执行异步函数,可选延迟
executeImmediate立即重新执行(相当于 execute(0) 的简写)

等待结果

返回值是可等待的,因此你可以在异步函数或 <script setup> 中使用 await

ts
const { 
state
,
isReady
} = await useAsyncState(fetchData, null)
// `state` 现在已经有数据了,`isReady` 为 true

手动执行

immediate: false 设置为不在创建时自动执行。

vue
<script setup lang="ts">
import { 
useAsyncState
} from '@vueuse/core'
const {
state
,
execute
,
executeImmediate
} =
useAsyncState
(
action
, '', {
immediate
: false })
async function
action
(
event
) {
await new
Promise
(
resolve
=>
setTimeout
(
resolve
, 500))
return `${
event
.target.textContent} 被点击啦!`
} </script> <template> <
p
>状态: {{
state
}}</
p
>
<
button
class
="button" @
click
="
executeImmediate
">
立即执行 </
button
>
<
button
class
="ml-2 button" @
click
="
event
=>
execute
(500,
event
)">
延迟执行 </
button
>
</template>

选项

ts
const { 
state
} = useAsyncState(promise, initialState, {
// 创建时是否立即执行(默认:true)
immediate
: true,
// 首次执行的延迟时间,单位毫秒(默认:0)
delay
: 0,
// 每次执行前是否重置状态为初始值(默认:true)
resetOnExecute
: true,
// 是否使用 shallowRef 作为状态(默认:true)
shallow
: true,
// 是否抛出错误而不是捕获(默认:false)
throwError
: false,
// Promise 解析时调用
onSuccess
(
data
) {
console
.
log
('成功:',
data
)
}, // Promise 拒绝时调用
onError
(
error
) {
console
.
error
('错误:',
error
)
}, })

类型声明

显示类型声明
ts
export interface 
UseAsyncStateReturnBase
<
Data
,
Params
extends any[],
Shallow
extends boolean,
> {
state
:
Shallow
extends true ?
Ref
<
Data
> :
Ref
<
UnwrapRef
<
Data
>>
isReady
:
Ref
<boolean>
isLoading
:
Ref
<boolean>
error
:
Ref
<unknown>
execute
: (
delay
?: number, ...
args
:
Params
) =>
Promise
<
Data
| undefined>
executeImmediate
: (...
args
:
Params
) =>
Promise
<
Data
| undefined>
} export type
UseAsyncStateReturn
<
Data
,
Params
extends any[],
Shallow
extends boolean,
> =
UseAsyncStateReturnBase
<
Data
,
Params
,
Shallow
> &
PromiseLike
<
UseAsyncStateReturnBase
<
Data
,
Params
,
Shallow
>>
export interface
UseAsyncStateOptions
<
Shallow
extends boolean,
D
= any> {
/** * Delay for the first execution of the promise when "immediate" is true. In milliseconds. * * @default 0 */
delay
?: number
/** * 在函数调用后立即执行 Promise。 * 如果设置了延迟,将应用延迟。 * * 当设置为 false 时,需要手动执行。 * * @default true */
immediate
?: boolean
/** * 捕获到错误时的回调。 */
onError
?: (
e
: unknown) => void
/** * 捕获到成功时的回调。 * @param {D} data */
onSuccess
?: (
data
:
D
) => void
/** * 在执行 Promise 前将状态设置为初始状态。 * * 当多次调用执行函数时(例如,刷新数据),这可能很有用。 * 当设置为 false 时, * 当前状态保持不变,直到 Promise 解析。 * * @default true */
resetOnExecute
?: boolean
/** * 使用 shallowRef。 * * @default true */
shallow
?:
Shallow
/** * * 在执行 execute 函数时抛出错误 * * @default false */
throwError
?: boolean
} /** * 响应式的异步状态。不会阻塞你的函数, * 并在 Promise 完成时触发更改。 * * @see https://vueuse.org/useAsyncState * @param promise 要解析的异步函数 * @param initialState 初始状态,在第一次评估完成之前使用 * @param options */ export declare function
useAsyncState
<
Data
,
Params
extends any[] = any[],
Shallow
extends boolean = true,
>(
promise
:
Promise
<
Data
> | ((...
args
:
Params
) =>
Promise
<
Data
>),
initialState
:
MaybeRef
<
Data
>,
options
?:
UseAsyncStateOptions
<
Shallow
,
Data
>,
):
UseAsyncStateReturn
<
Data
,
Params
,
Shallow
>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
丶远方
James Garbutt
Flamenco
machete
Vida Xie
Andrew Kazakov
Jialong Lu
duyifei
David Gonzalez
Robin
Robin
Joris Gallot
Jules Raffoux
hfutsora
Brain777777
Mao Mr
Jelf
Sergey Shumov
lsdsjy
IIFelix
Alex Francev
webfansplz
Shinigami
Shahar Kosti
Alex Kozack
ordago
Jacob Clevenger
Antério Vieira

更新日志

0c346 - fix: ensure execute return the actual data (#5167)
3e6cb - fix: track latest execution to avoid newer results being replaced by outdated ones (#5047)
e38e8 - feat: allow initial value to be a ref (#4992)
f6e88 - feat!: set globalThis.reportError as default onError (#4951)
82740 - feat: add executeImmediate with the same type as the promise fn (#4716)
4d0a7 - fix: use ShallowRef instead of Ref type (#4294)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)