跳到主要内容

computedAsync

分类
导出大小
360 B
上次更改
上个月
别名
asyncComputed

异步函数的计算属性

演示

正在评估: false
null

用法

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
name
=
shallowRef
('jack')
const
userInfo
=
computedAsync
(
async () => { return await mockLookUp(
name
.
value
)
}, null, /* initial state */ )

评估状态

你需要传入一个 ref 来跟踪异步函数是否正在评估。

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
evaluating
=
shallowRef
(false)
const
userInfo
=
computedAsync
(
async () => { /* your logic */ }, null,
evaluating
,
)

onCancel

当计算属性的源在之前的异步函数解析之前发生变化时,你可能希望取消之前的函数。这是一个如何与 fetch API 结合使用的例子。

ts
const 
packageName
=
shallowRef
('@vueuse/core')
const
downloads
=
computedAsync
(async (
onCancel
) => {
const
abortController
= new
AbortController
()
onCancel
(() =>
abortController
.
abort
())
return await
fetch
(
`https://api.npmjs.org/downloads/point/last-week/${
packageName
.
value
}`,
{
signal
:
abortController
.
signal
},
) .
then
(
response
=>
response
.
ok
?
response
.
json
() : {
downloads
: '' })
.
then
(
result
=>
result
.downloads)
}, 0)

惰性加载

默认情况下,computedAsync 会在创建时立即开始解析,指定 lazy: true 可以使其在第一次访问时才开始解析。

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
evaluating
=
shallowRef
(false)
const
userInfo
=
computedAsync
(
async () => { /* your logic */ }, null, {
lazy
: true,
evaluating
},
)

注意事项

  • 与 Vue 内置的 computed 函数一样,computedAsync 会进行依赖跟踪,并在依赖项改变时自动重新评估。但请注意,只有在第一次调用栈中引用的依赖项才会被考虑。换句话说:异步访问的依赖项不会触发异步计算值的重新评估。

  • 与 Vue 内置的 computed 函数不同,异步计算值的重新评估会在依赖项改变时触发,无论其结果当前是否正在被跟踪。

类型声明

显示类型声明
ts
/**
 * Handle overlapping async evaluations.
 *
 * @param cancelCallback The provided callback is invoked when a re-evaluation of the computed value is triggered before the previous one finished
 */
export type 
AsyncComputedOnCancel
= (
cancelCallback
:
Fn
) => void
export interface
AsyncComputedOptions
<
Lazy
= boolean> {
/** * Should value be evaluated lazily * * @default false */
lazy
?:
Lazy
/** * Ref passed to receive the updated of async evaluation */
evaluating
?:
Ref
<boolean>
/** * Use shallowRef * * @default true */
shallow
?: boolean
/** * The flush option allows for greater control over the timing of a history point, default to `pre` * * Possible values: `pre`, `post`, `sync` * * It works in the same way as the flush option in watch and watch effect in vue reactivity * @default 'sync' */
flush
?:
WatchOptionFlush
/** * Callback when error is caught. */
onError
?: (
e
: unknown) => void
} /** * Create an asynchronous computed dependency. * * @see https://vueuse.org.cn/computedAsync * @param evaluationCallback The promise-returning callback which generates the computed value * @param initialState The initial state, used until the first evaluation finishes * @param optionsOrRef Additional options or a ref passed to receive the updates of the async evaluation */ export declare function
computedAsync
<
T
>(
evaluationCallback
: (
onCancel
:
AsyncComputedOnCancel
) =>
T
|
Promise
<
T
>,
initialState
:
T
,
optionsOrRef
:
AsyncComputedOptions
<true>,
):
ComputedRef
<
T
>
export declare function
computedAsync
<
T
>(
evaluationCallback
: (
onCancel
:
AsyncComputedOnCancel
) =>
T
|
Promise
<
T
>,
initialState
: undefined,
optionsOrRef
:
AsyncComputedOptions
<true>,
):
ComputedRef
<
T
| undefined>
export declare function
computedAsync
<
T
>(
evaluationCallback
: (
onCancel
:
AsyncComputedOnCancel
) =>
T
|
Promise
<
T
>,
initialState
:
T
,
optionsOrRef
?:
Ref
<boolean> |
AsyncComputedOptions
,
):
Ref
<
T
>
export declare function
computedAsync
<
T
>(
evaluationCallback
: (
onCancel
:
AsyncComputedOnCancel
) =>
T
|
Promise
<
T
>,
initialState
?: undefined,
optionsOrRef
?:
Ref
<boolean> |
AsyncComputedOptions
,
):
Ref
<
T
| undefined>
/** @deprecated use `computedAsync` instead */ export declare const
asyncComputed
: typeof
computedAsync

来源

源文件示例文档

贡献者

Anthony Fu
Fernando Fernández
Anthony Fu
xiankaiqun
Arthur Darkstone
Vida Xie
bab
Yu Lia
SerKo
IlyaL
OrbisK
Icey Wu
sun0day
Yugang Cao
Bodo Graumann

更新日志

e5f74 - feat!: 弃用别名导出,转而使用原始函数名称 (#5009)
573bf - feat!: 默认使用 flush: sync (#4752)
v13.7.0
226a2 - feat: 默认使用 globalThis.reportError 作为 onError (#4943)
v13.3.0
217cc - fix(asyncComputed): 修复 AsyncComputedOptions 的类型
v13.2.0
b1718 - fix: 当 lazy: true 时返回 ComputedRef 类型 (#4751)
b1bc8 - feat: 添加控制 watcher 刷新时机的选项 (#4746)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v11.1.0
45b18 - fix: 类型签名 (#4207)

根据 MIT 许可证发布。