Vize

vize:croquis/cf/dom-access-without-next-tick

Vue が更新を反映する前に DOM を読んでいます。

既定の重大度 自動修正 オプション
現在は生成されません なし。関連ファイルを確認して修正してください コード固有のオプションはありません。対応済みの CLI の診断は、重大度を変更できます

適用範囲: 解析対象のコンポーネント構成と、下記に示す対応済みの情報

この公開診断コードには現在の生成元がありません。悪い例・良い例はリスクと修正の説明です。このコードを検出させる設定は現在ありません。

共通のプロジェクト ファイル

以下のファイルは、悪い例・良い例の両方で変更せずに使います。プロジェクトには Vue をインストールし、例で import している場合は vue-router や Pinia もインストールしてください。バージョン固有の対応条件がある場合は、その注意に従ってください。エントリーファイルによって、コンポーネント間の関係を明示しています。

main.ts

import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');

index.html

<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><title>Contract scenario</title></head>
<body><div id="app"></div><script type="module" src="/main.ts"></script></body></html>

read-label.ts

export function readLabel(node: HTMLElement | null): string {
  return node?.textContent ?? '';
}

悪い例

クリック処理が count を増やしてすぐ段落の DOM を読み、Vue による更新の反映を待っていません。sampled に前の count が入る可能性があります。

App.vue

<script setup lang="ts">
import { ref } from 'vue';
import { readLabel } from './read-label';
const count = ref(0);
const label = ref<HTMLElement | null>(null);
const sampled = ref('');
function increment() {
  count.value++;
  sampled.value = readLabel(label.value);
}
</script>

<template>
<button @click="increment">Increment</button><p ref="label">{{ count }}</p><p>DOM sample: {{ sampled }}</p>
</template>

良い例

状態を更新した後に nextTick() を待ち、Vue が段落を更新してから readLabel でテキストを読みます。

App.vue

<script setup lang="ts">
import { nextTick, ref } from 'vue';
import { readLabel } from './read-label';
const count = ref(0);
const label = ref<HTMLElement | null>(null);
const sampled = ref('');
async function increment() {
  count.value++;
  await nextTick();
  sampled.value = readLabel(label.value);
}
</script>

<template>
<button @click="increment">Increment</button><p ref="label">{{ count }}</p><p>DOM sample: {{ sampled }}</p>
</template>

設定(Vite+)

この診断コードは現在 CLI では出力されないため、有効化する CLI のルール設定はありません。

関連ページ

公開の説明

ファイル間ルール一覧