vize:croquis/cf/dom-access-without-next-tick
在 Vue 完成更新刷新之前读取 DOM。
| 默认严重程度 | 自动修复 | 选项 |
|---|---|---|
| 不产生诊断 | 无;请检查相关文件并应用修复 | 无针对单个诊断代码的选项;受支持的 CLI 诊断可覆盖严重程度 |
适用范围: 已分析的组件图,以及下方说明的受支持事实
这是目前没有实现的公开诊断约定。下方错误与正确示例解释风险及修复;目前没有任何标志能使此诊断代码触发。
共享项目文件
错误和正确示例都使用这些不变的文件。在项目中安装导入的包:Vue,以及示例中出现的 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 后立即读取渲染段落,此时 Vue 尚未刷新计划中的 DOM 更新。sampled 可能包含之前的计数。
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 规则配置。