computedAsync
用于异步函数的计算属性
用法
js
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 来跟踪异步函数是否正在评估。
js
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const evaluating = shallowRef(false)
const userInfo = computedAsync(
async () => { /* your logic */ },
null,
evaluating,
)
onCancel
当计算源在先前的异步函数解析之前发生更改时,您可能需要取消先前的异步函数。这是一个展示如何与 fetch API 结合使用的示例。
js
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
使其在首次访问时开始解析。
js
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
函数相反,每当依赖项发生更改时,无论其结果当前是否正在被跟踪,都会触发异步计算值的重新评估。
类型声明
显示类型声明
typescript
/**
* 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 {
/**
* Should value be evaluated lazily
*
* @default false
*/
lazy?: boolean
/**
* Ref passed to receive the updated of async evaluation
*/
evaluating?: Ref<boolean>
/**
* Use shallowRef
*
* @default true
*/
shallow?: boolean
/**
* 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?: 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>
export { computedAsync as asyncComputed }