computedAsync
用于异步函数的计算属性
示例
Evaluating: 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, /* 初始状态 */
)Evaluation 参数
你需要传递一个 ref 来跟踪异步函数的状态。
ts
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const evaluating = shallowRef(false)
const userInfo = computedAsync(
async () => { /* 你的逻辑 */ },
null,
evaluating, // can also be passed via options: { evaluating }
)js
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const evaluating = shallowRef(false)
const userInfo = computedAsync(
async () => {
/* 你的逻辑 */
},
null,
evaluating,
)onCancel
当计算源在前一个异步函数解决之前发生变化时,你可能希望取消前一个函数。以下是如何与 fetch API 结合使用的示例。
ts
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
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 () => { /* 你的逻辑 */ },
null,
{ lazy: true, evaluating },
)错误处理
使用 onError 回调处理异步函数中的错误。
ts
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const name = shallowRef('jack')
const userInfo = computedAsync(
async () => {
return await mockLookUp(name.value)
},
null,
{
onError(e) {
console.error('获取用户信息失败', e)
},
},
)浅层 Ref
默认情况下,computedAsync 内部使用 shallowRef。设置 shallow: false 可改用深层响应式。
ts
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const name = shallowRef('jack')
const userInfo = computedAsync(
async () => {
return await fetchNestedData(name.value)
},
null,
{ shallow: false }, // 启用深层响应式
)js
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const name = shallowRef('jack')
const userInfo = computedAsync(
async () => {
return await fetchNestedData(name.value)
},
null,
{ shallow: false },
)注意事项
与 Vue 内置的
computed函数相似,computedAsync会进行依赖跟踪,并在依赖更改时自动重新计算。注意,只有在第一次调用堆栈中引用的依赖才会被考虑。换句话说:异步访问的依赖不会触发异步计算值的重新评估。与 Vue 内置的
computed函数相反,无论其结果当前是否被跟踪,异步计算值的重新评估都会在依赖项发生更改时触发。
类型声明
显示类型声明
ts
/**
* 清除计算属性的副作用
*
* @param cancelCallback 当触发计算值的重新计算时,调用提供的回调函数
*/
export type AsyncComputedOnCancel = (cancelCallback: Fn) => void
export interface AsyncComputedOptions<
Lazy = boolean,
> extends ConfigurableFlushSync {
/**
* 是否应该延迟评估值
*
* @default false
*/
lazy?: Lazy
/**
* 传递的 Ref 以接收异步评估的更新
*/
evaluating?: Ref<boolean>
/**
* 使用 shallowRef
*
* @default true
*/
shallow?: boolean
/**
* 捕获到错误时的回调函数。
*/
onError?: (e: unknown) => void
}
/**
* 创建一个计算属性,其值是通过异步回调函数生成的。
*
* @see https://vueuse.org/computedAsync
* @param evaluationCallback 生成计算值的返回 Promise 的回调函数
* @param initialState 初始状态,在第一次执行完成之前使用
* @param optionsOrRef 额外选项或传递的 Ref 以接收异步状态的更新
*/
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