Skip to content

computedAsync

類別
導出大小
347 B
上次更改
3 週前
別名
asyncComputed

用於異步函數的 computed

用法

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

當 computed 來源在先前的異步函數解析之前發生更改時,您可能想要取消先前的異步函數。以下是如何與 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` 會進行依賴追蹤,並在依賴項更改時自動重新評估。但請注意,只有在第一個調用堆疊中引用的依賴項才被考慮用於此。換句話說:**異步訪問的依賴項不會觸發異步 computed 值的重新評估。**

  • 與 Vue 的內建 `computed` 函數相反,無論異步 computed 值的結果目前是否正在被追蹤,只要依賴項發生更改,就會觸發異步 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.dev.org.tw/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 }

原始碼

原始碼文件

貢獻者

Anthony Fu
Anthony Fu
xiankaiqun
IlyaL
OrbisK
Fernando Fernández
Icey Wu
sun0day
Yugang Cao
Bodo Graumann

更新日誌

v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v11.1.0 於 2024/9/16
45b18 - fix: type signature (#4207)
v10.0.0-beta.0 於 2023/3/14
23c9d - feat!: set shallow defalut to true (#2621)

根據 MIT 許可證發布。