computedAsync
非同期関数の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 }