computedAsync
用於異步函數的 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 }