コンテンツへスキップ

computedAsync

カテゴリ
エクスポートサイズ
358 B
最終変更日
先週
エイリアス
asyncComputed

非同期関数のComputed

使用方法

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
)

評価状態

非同期関数の評価中かどうかを追跡するためのrefを渡す必要があります。

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

const evaluating = ref(false)

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

onCancel

前の非同期関数が解決される前にcomputedソースが変更された場合、前の非同期関数をキャンセルしたい場合があります。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)

遅延実行

デフォルトでは、computedAsyncは作成時にすぐに解決を開始しますが、lazy: trueを指定すると、初回アクセス時に解決を開始します。

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

const evaluating = ref(false)

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

注意点

  • Vueの組み込みcomputed関数と同様に、computedAsyncは依存関係の追跡を行い、依存関係が変更されると自動的に再評価されます。ただし、最初の呼び出しスタックで参照される依存関係のみが考慮されることに注意してください。言い換えれば、**非同期的にアクセスされる依存関係は、非同期computed値の再評価をトリガーしません。**

  • Vueの組み込み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.dokyumento.jp/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
xiankaiqun
Anthony Fu
Fernando Fernández
Icey Wu
sun0day
Yugang Cao
Bodo Graumann

変更ログ

v12.0.0-beta.1 2024年11月21日
0a9ed - feat!: Vue 2サポートの削除、バンドルの最適化、クリーンアップ (#4349)
v11.1.0 2024年9月16日
45b18 - fix: 型シグネチャ (#4207)
v10.0.0-beta.0 2023年3月14日
23c9d - feat!: デフォルトのshallowをtrueに設定 (#2621)
v9.11.0 2023年1月17日
a0656 - feat: shadow オプションの導入 (#2616)

MITライセンスの下でリリースされています。