Skip to content

computedAsync

为异步函数计算

¥Computed for async functions

用法

¥Usage

js
import { computedAsync } from '@vueuse/core'
import { ref } from 'vue'

const name = ref('jack')

const userInfo = computedAsync(
  async () => {
    return await mockLookUp(name.value)
  },
  null, // initial state
)

评价状态

¥Evaluation State

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

¥You will need to pass a ref to track if the async function is evaluating.

js
import { computedAsync } from '@vueuse/core'
import { ref } from 'vue'

const evaluating = ref(false)

const userInfo = computedAsync(
  async () => { /* your logic */ },
  null,
  evaluating,
)

onCancel

当计算源在前一个异步函数解决之前发生更改时,你可能需要取消前一个异步函数。以下示例展示了如何与 fetch API 结合使用。

¥When the computed source changed before the previous async function gets resolved, you may want to cancel the previous one. Here is an example showing how to incorporate with the fetch API.

js
const packageName = ref('@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)

懒惰的

¥Lazy

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

¥By default, computedAsync will start resolving immediately on creation, specify lazy: true to make it start resolving on the first accessing.

js
import { computedAsync } from '@vueuse/core'
import { ref } from 'vue'

const evaluating = ref(false)

const userInfo = computedAsync(
  async () => { /* your logic */ },
  null,
  { lazy: true, evaluating },
)

注意事项

¥Caveats

  • 就像 Vue 内置的 computed 函数一样,computedAsync 进行依赖跟踪,并在依赖发生变化时自动重新评估。但请注意,仅考虑第一个调用堆栈中引用的依赖。换句话说:异步访问的依赖不会触发异步计算值的重新计算。

    ¥Just like Vue's built-in computed function, computedAsync does dependency tracking and is automatically re-evaluated when dependencies change. Note however that only dependency referenced in the first call stack are considered for this. In other words: Dependencies that are accessed asynchronously will not trigger re-evaluation of the async computed value.

  • 与 Vue 的内置 computed 函数相反,只要依赖发生变化,就会触发异步计算值的重新评估,无论其结果当前是否正在被跟踪。

    ¥As opposed to Vue's built-in computed function, re-evaluation of the async computed value is triggered whenever dependencies are changing, regardless of whether its result is currently being tracked or not.

类型声明

显示类型声明
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/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 }

源代码

源代码文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号