script/no-async-in-computed
computed の getter で非同期関数を使う箇所を検出します。
既定の重大度: error
プリセット: essential, happy-path, ecosystem, nuxt, opinionated
自動修正: なし。修正内容を確認してください
適用範囲: Vue SFC の JS / TS script。Options API または script setup の対象は例を参照してください。
オプション: ルール固有のオプションはありません。重大度とプリセットは設定できます。
設定(Vite+)
import { defineConfig } from "@vizejs/vite-plugin/vite-plus";
export default defineConfig({
lint: {
vize: {
"preset": "incremental",
"rules": {
"script/no-async-in-computed": "error"
}
},
},
});
vp run lint
悪い
computed の getter が async であり、fetch の結果を同期的な計算値ではなく Promise として返します。
<script setup lang="ts">
import { computed } from "vue";
const data = computed(async () => {
const response = await fetch("/api/data");
return response.json();
});
</script>
良い
非同期の fetch を watch に移し、結果を data.value に保存します。クリーンアップで古い要求を中止し、無効になったコールバックが古い結果を書き込むのを防ぎます。async な computed getter は残りません。
<script setup lang="ts">
import { ref, watch } from "vue";
const query = ref("");
const data = ref<unknown>(null);
watch(query, async (value, _oldValue, onCleanup) => {
const controller = new AbortController();
let active = true;
onCleanup(() => { active = false; controller.abort(); });
const response = await fetch(`/api/data?q=${encodeURIComponent(value)}`, { signal: controller.signal });
const next: unknown = await response.json();
if (active) data.value = next;
});
</script>
良い例は上記の設定でこのルールの検出を避ける例です。他のルールでは検出される場合があります。