computedAsync
computedAsync
非同期関数のためのComputed
使用法
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const name = shallowRef('jack')
const userInfo = computedAsync(
async () => {
return await mockLookUp(name.value)
},
null, /* 初期状態 */
)
評価状態
非同期関数が評価中であるかを追跡するために、refを渡す必要があります。
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const evaluating = shallowRef(false)
const userInfo = computedAsync(
async () => { /* あなたのロジック */ },
null,
evaluating,
)
onCancel
前の非同期関数が解決される前にcomputedのソースが変更された場合、前のものをキャンセルしたいかもしれません。ここではfetch APIと組み合わせる方法を示します。
import { computedAsync } from '@vueuse/core'
// ---cut---
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を指定すると、最初にアクセスされたときに解決を開始します。
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const evaluating = shallowRef(false)
const userInfo = computedAsync(
async () => { /* あなたのロジック */ },
null,
{ lazy: true, evaluating },
)
注意点
-
Vueの組み込みの
computed関数と同様に、computedAsyncは依存関係の追跡を行い、依存関係が変化すると自動的に再評価されます。ただし、最初のコールスタックで参照された依存関係のみがこれに考慮されます。つまり、非同期にアクセスされた依存関係は、非同期computed値の再評価をトリガーしません。 -
Vueの組み込みの
computed関数とは異なり、非同期computed値の再評価は、結果が現在追跡されているかどうかに関係なく、依存関係が変化するたびにトリガーされます。
© 2019–PRESENT Anthony Fu https://github.com/antfu
※このページは Nuxt.js 公式ドキュメントの翻訳ページです。
公式ドキュメントの該当ページはこちら:
#