Vue3 组合式 API
深入讲解 Vue 3 组合式 API(Composition API)的逻辑聚合优势、setup()、ref/reactive/computed、生命周期钩子映射、模板引用、watchEffect flush:'post' 及 48 项核心 API 手册,并附 ES Proxy Chromium 实测。
学完这一章,你能够
- 深入讲解 Vue 3 组合式 API(Composition API)的逻辑聚合优势、setup()、ref/reactive/computed、生命周期钩子映射、模板引用、watchEffect flush:'post' 及 48 项核心 API 手册,并附 ES Proxy Chromium 实测。
组合式 API 动机与 setup() 入口
随着业务复杂度上升,选项式 API(Options API)会把同一功能的数据、计算属性、方法与侦听器拆分到不同选项块中,阅读与复用成本陡增。Vue 3 的组合式 API(Composition API)以 `setup` 为入口,允许按逻辑关注点就近组织代码并抽离为可复用的组合式函数(Composables)。
`setup(props, context)` 在组件创建(`created` 之前)阶段执行:第一参数 `props` 是响应式对象(随父组件更新),第二参数 `context` 是普通对象,暴露 `attrs`、`slots`、`emit` 与 `expose`。由于此时 `data`、`computed` 与 `methods` 尚未解析,组件实例未就绪,因此在 `setup` 内应避免使用 `this`。`setup` 返回的对象属性与函数会直接暴露给模板渲染。
为了使基本类型(数字、字符串、布尔等)也能具备响应性,Vue 3 提供 `ref()` 函数将其包装为带 `.value` 属性的响应式引用对象:在 `setup()` 脚本内读写需访问 `.value`,而在模板中渲染时会自动浅层解包。本站离线 Chromium 基于 ES Proxy 实测:`count = ref(0)` 与 `doubled = computed(() => count.value * 2)` 初次多次读取仅计算 `1` 次(缓存生效),点击按钮自增后 DOM 同步更新为 `1/2` 且计算次数升为 `2`;同时验证了 `readonly` 拦截写操作、`toRefs` 同步原响应式对象以及 `isRef`/`unref`/`toValue`/`isProxy`/`isReactive`/`isReadonly`/`toRaw`/`markRaw` 全部判定准确。
组合式 API 生命周期钩子与作用域管理
在 Vue 2 选项式 API 中直接声明 `beforeMount`、`mounted` 等方法,而在 Vue 3 `setup()` 内则导入带 `on` 前缀的钩子函数(如 `onBeforeMount`、`onMounted`)并传入回调。由于 `setup()` 本身围绕 `beforeCreate` 与 `created` 阶段运行,这两个生命周期无需单独注册,直接写在 `setup()` 顶层即可。本站离线 Chromium 实测验证完整生命周期按 `setup -> onBeforeMount -> onMounted -> onBeforeUpdate -> onUpdated -> onBeforeUnmount -> onUnmounted` 触发,同时验证 `provide`/`inject` 跨层传递 `'sky-blue'` 以及 `effectScope().stop()` 触发 `onScopeDispose` 并自动停止作用域内副作用。
模板引用、v-for 函数引用与 flush: 'post'
组合式 API 将响应式引用与模板引用统一起来:声明 `const root = ref(null)` 并从 `setup()` 返回,在模板中写 `<div ref="root">` 后,初始挂载完成时真实 DOM 节点便会自动写入 `root.value`,且该 `ref` 可像普通响应式引用一样传入组合式函数。
当需要在 `v-for` 列表内收集多个 DOM 节点引用时,可使用函数型 `:ref="el => { if (el) divs[i] = el }"`,并配合 `onBeforeUpdate(() => { divs.value = [] })` 在每次重渲染前清空旧数组以避免残留引用。本站实测 `rootRef` 挂载前为 `null`、挂载后为 `DIV`,列表更新前后函数引用数组精确记录 `['1','2','3']` 与 `['10','20']`。
用 `watch()` 或 `watchEffect()` 侦听模板引用时需留意执行时机:默认 `flush: 'pre'` 会在 DOM 挂载或更新之前运行副作用,此时 `root.value` 仍为 `null`;只有传入 `{ flush: 'post' }`(或使用 `watchPostEffect`),回调才会在 DOM 更新后执行,从而访问到已同步的 DOM 元素。本站离线 Chromium 实测:默认 `watchEffect` 首次观测到 `null`,而 `flush: 'post'` 首次即观测到真实节点 ID `'tpl-root'`;同时验证了 `watch` 的清理回调在每次值变更前及停止监听时准确按序执行。
组合式 API 核心手册
下表与前文生命周期映射表完整整理了 Vue 3 组合式 API 的 48 项核心接口,涵盖响应式核心(`ref`/`reactive`/`computed`/`readonly`)、侦听器(`watch`/`watchEffect`/`onWatcherCleanup`)、工具函数(`toRef`/`toRefs`/`toValue`)、进阶控制(`shallowRef`/`customRef`/`toRaw`/`markRaw`/`effectScope`)、生命周期钩子、依赖注入(`provide`/`inject`)与组件辅助函数(`useAttrs`/`useSlots`/`useModel`/`useTemplateRef`/`useId`)。
Options API 与 Composition API 生命周期映射
| Vue 2 Options API | Vue 3 Composition API |
| beforeCreate | 直接写在 setup() 中 |
| created | 直接写在 setup() 中 |
| beforeMount | onBeforeMount |
| mounted | onMounted |
| beforeUpdate | onBeforeUpdate |
| updated | onUpdated |
| beforeDestroy | onBeforeUnmount |
| destroyed | onUnmounted |
| errorCaptured | onErrorCaptured |
Vue 3 Composition API 核心接口手册
| 序号 | API 与功能说明 | 典型示例 |
| 1 | setup():组合式 API 入口函数,初始化响应式状态与方法 | export default { setup() { const count = ref(0); return { count } } } |
| 2 | ref():创建带 .value 的响应式引用,适用基本类型或对象 | const count = ref(0) |
| 3 | computed():创建带缓存的响应式计算属性 | const doubled = computed(() => count.value * 2) |
| 4 | reactive():基于 Proxy 创建深层响应式对象或数组 | const state = reactive({ count: 0 }) |
| 5 | readonly():创建深层只读代理,阻止直接修改 | const ro = readonly({ count: 0 }) |
| 6 | watchEffect():立即执行并自动追踪依赖的响应式副作用 | watchEffect(() => console.log(count.value)) |
| 7 | watchPostEffect():等价 flush:'post',在 DOM 更新后执行副作用 | watchPostEffect(() => console.log(root.value)) |
| 8 | watchSyncEffect():等价 flush:'sync',依赖变更时同步触发副作用 | watchSyncEffect(() => console.log(count.value)) |
| 9 | watch():显式侦听一个或多个响应式数据源并获取新旧值 | watch(count, (nv, ov) => console.log(nv, ov)) |
| 10 | onWatcherCleanup():Vue 3.5+ 在侦听回调内注册副作用清理函数 | watch(id, () => { onWatcherCleanup(cancel) }) |
| 11 | isRef():判断某个值是否为 ref 对象 | isRef(count) |
| 12 | unref():若是 ref 则返回 .value,否则返回原值 | unref(count) |
| 13 | toRef():为响应式对象属性或 getter 创建保持同步的 ref | const nRef = toRef(state, 'n') |
| 14 | toValue():将值、ref 或 getter 函数统一规范为普通值 | toValue(() => 7) |
| 15 | toRefs():将响应式对象每个属性转为独立 ref 以安全解构 | const { n } = toRefs(state) |
| 16 | isProxy():检测对象是否由 reactive/readonly 等创建代理 | isProxy(state) |
| 17 | isReactive():检测对象是否为响应式代理 | isReactive(state) |
| 18 | isReadonly():检测对象是否为只读代理 | isReadonly(ro) |
| 19 | shallowRef():浅层 ref,仅追踪 .value 整体替换而非深层属性 | const s = shallowRef({ count: 0 }) |
| 20 | triggerRef():手动强制触发 shallowRef 关联副作用更新 | triggerRef(s) |
| 21 | customRef():自定义依赖收集(track)与更新派发(trigger) | customRef((track, trigger) => ({ get(){}, set(v){} })) |
| 22 | shallowReactive():仅根层属性具备响应性的浅层代理 | const s = shallowReactive({ count: 0 }) |
| 23 | shallowReadonly():仅根层属性只读的浅层代理 | const s = shallowReadonly({ count: 0 }) |
| 24 | toRaw():返回 Vue 代理包装背后的原始对象 | const raw = toRaw(state) |
| 25 | markRaw():标记对象永久跳过代理转换 | const plain = markRaw({ count: 0 }) |
| 26 | effectScope():创建副作用作用域以集中捕获并统一销毁 | const scope = effectScope() |
| 27 | getCurrentScope():返回当前活跃的 effectScope 实例 | const cur = getCurrentScope() |
| 28 | onScopeDispose():注册当前作用域停止时执行的清理回调 | onScopeDispose(() => cleanup()) |
| 29 | onMounted():组件挂载至 DOM 后调用 | onMounted(() => {}) |
| 30 | onUpdated():响应式变更导致 DOM 更新后调用 | onUpdated(() => {}) |
| 31 | onUnmounted():组件卸载完成后调用,适合释放定时器/监听 | onUnmounted(() => {}) |
| 32 | onBeforeMount():组件挂载到 DOM 之前调用 | onBeforeMount(() => {}) |
| 33 | onBeforeUpdate():DOM 因响应式更新重渲染前调用 | onBeforeUpdate(() => {}) |
| 34 | onBeforeUnmount():组件实例卸载之前调用 | onBeforeUnmount(() => {}) |
| 35 | onErrorCaptured():捕获后代组件传播的错误 | onErrorCaptured((err, inst, info) => {}) |
| 36 | onRenderTracked():开发模式调试钩子,追踪渲染依赖时触发 | onRenderTracked((e) => {}) |
| 37 | onRenderTriggered():开发模式调试钩子,依赖触发重渲染时调用 | onRenderTriggered((e) => {}) |
| 38 | onActivated():被 <KeepAlive> 缓存的组件重新激活时调用 | onActivated(() => {}) |
| 39 | onDeactivated():被 <KeepAlive> 缓存的组件失活停用时调用 | onDeactivated(() => {}) |
| 40 | onServerPrefetch():SSR 服务端渲染期间异步预取数据 | onServerPrefetch(async () => await load()) |
| 41 | provide():向所有后代组件提供可注入数据 | provide('theme', 'sky-blue') |
| 42 | inject():在后代组件注入祖先提供的数据 | const theme = inject('theme') |
| 43 | hasInjectionContext():检查当前调用栈是否允许调用 inject() | hasInjectionContext() |
| 44 | useAttrs():在 <script setup> 中获取透传 attrs 对象 | const attrs = useAttrs() |
| 45 | useSlots():在 <script setup> 中获取组件插槽对象 | const slots = useSlots() |
| 46 | useModel():底层辅助函数,驱动 defineModel 双向绑定 | const model = useModel(props, 'modelValue') |
| 47 | useTemplateRef():Vue 3.5+ 按模板 ref 名获取浅层 DOM 引用 | const input = useTemplateRef('my-input') |
| 48 | useId():Vue 3.5+ 生成跨 SSR 与客户端一致的唯一无障碍 ID | const id = useId() |
在离线 Chromium 中验证 ES Proxy 响应式核心、生命周期、模板引用与 flush:'post'
展开查看收起
"""Offline Playwright Chromium lab for Vue 3 Ch 28: Composition API reactivity & lifecycle."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Composition API Lab</title>
</head>
<body>
<div id="counter-text"></div>
<button id="counter-btn">+1</button>
<div id="tpl-root">This is a root element</div>
<div id="list-box"></div>
<script>
// Minimal offline Vue 3 Composition API reactivity core (ES Proxy)
let activeEffect = null;
let activeScope = null;
const targetMap = new WeakMap();
const RAW_SYM = Symbol('raw');
const REACTIVE_SYM = Symbol('isReactive');
const READONLY_SYM = Symbol('isReadonly');
const SKIP_SYM = Symbol('markRaw');
function track(target, key) {
if (!activeEffect) return;
let depsMap = targetMap.get(target);
if (!depsMap) targetMap.set(target, (depsMap = new Map()));
let dep = depsMap.get(key);
if (!dep) depsMap.set(key, (dep = new Set()));
dep.add(activeEffect);
activeEffect.deps.add(dep);
}
function trigger(target, key) {
const depsMap = targetMap.get(target);
if (!depsMap) return;
const dep = depsMap.get(key);
if (!dep) return;
[...dep].forEach(eff => {
if (eff.scheduler) eff.scheduler();
else eff.run();
});
}
function reactive(obj) {
if (!obj || typeof obj !== 'object' || obj[SKIP_SYM]) return obj;
return new Proxy(obj, {
get(target, key, receiver) {
if (key === RAW_SYM) return target;
if (key === REACTIVE_SYM) return true;
const res = Reflect.get(target, key, receiver);
track(target, key);
return res && typeof res === 'object' ? reactive(res) : res;
},
set(target, key, value, receiver) {
const oldVal = target[key];
const ok = Reflect.set(target, key, value, receiver);
if (oldVal !== value) trigger(target, key);
return ok;
}
});
}
function readonly(obj) {
return new Proxy(obj, {
get(target, key, receiver) {
if (key === RAW_SYM) return target;
if (key === READONLY_SYM) return true;
return Reflect.get(target, key, receiver);
},
set() { return true; } // silently ignore write like Vue readonly
});
}
function ref(initial) {
const wrapper = {
__v_isRef: true,
_value: initial,
get value() { track(wrapper, 'value'); return wrapper._value; },
set value(v) {
if (v !== wrapper._value) {
wrapper._value = v;
trigger(wrapper, 'value');
}
}
};
return wrapper;
}
function isRef(v) { return Boolean(v && v.__v_isRef); }
function unref(v) { return isRef(v) ? v.value : v; }
function toValue(v) { return typeof v === 'function' ? v() : unref(v); }
function isReactive(v) { return Boolean(v && v[REACTIVE_SYM]); }
function isReadonly(v) { return Boolean(v && v[READONLY_SYM]); }
function isProxy(v) { return isReactive(v) || isReadonly(v); }
function toRaw(v) { return (v && v[RAW_SYM]) || v; }
function markRaw(v) { Object.defineProperty(v, SKIP_SYM, { value: true }); return v; }
function toRef(obj, key) {
return {
__v_isRef: true,
get value() { return obj[key]; },
set value(v) { obj[key] = v; }
};
}
function toRefs(obj) {
const res = {};
for (const k of Object.keys(obj)) res[k] = toRef(obj, k);
return res;
}
function computed(getter) {
let dirty = true;
let cached;
let computeCount = 0;
const eff = {
deps: new Set(),
run() {
const prev = activeEffect;
activeEffect = eff;
try { cached = getter(); computeCount++; } finally { activeEffect = prev; }
dirty = false;
return cached;
},
scheduler() {
if (!dirty) { dirty = true; trigger(cRef, 'value'); }
}
};
const cRef = {
__v_isRef: true,
get _computeCount() { return computeCount; },
get value() {
track(cRef, 'value');
if (dirty) eff.run();
return cached;
}
};
return cRef;
}
function effectScope() {
const stops = [];
const cleanups = [];
const scope = {
active: true,
run(fn) {
const prev = activeScope;
activeScope = scope;
try { return fn(); } finally { activeScope = prev; }
},
recordStop(fn) { stops.push(fn); },
onDispose(fn) { cleanups.push(fn); },
stop() {
if (!scope.active) return;
scope.active = false;
stops.forEach(s => s());
cleanups.forEach(c => c());
}
};
return scope;
}
function getCurrentScope() { return activeScope; }
function onScopeDispose(fn) { if (activeScope) activeScope.onDispose(fn); }
function watchEffect(fn, options = {}) {
const flush = options.flush || 'pre';
let cleanup = null;
let stopped = false;
const onCleanup = (cb) => { cleanup = cb; };
const eff = {
deps: new Set(),
run() {
if (stopped) return;
if (cleanup) { cleanup(); cleanup = null; }
const prev = activeEffect;
activeEffect = eff;
try { fn(onCleanup); } finally { activeEffect = prev; }
},
scheduler() {
if (stopped) return;
if (flush === 'post') Promise.resolve().then(() => eff.run());
else eff.run();
}
};
if (flush === 'post') Promise.resolve().then(() => eff.run());
else eff.run();
const stop = () => {
stopped = true;
if (cleanup) { cleanup(); cleanup = null; }
eff.deps.forEach(d => d.delete(eff));
};
if (activeScope) activeScope.recordStop(stop);
return stop;
}
function watch(source, cb) {
let oldVal = isRef(source) ? source.value : source();
let cleanup = null;
const registerCleanup = (fn) => { cleanup = fn; };
const eff = {
deps: new Set(),
run() {
const prev = activeEffect;
activeEffect = eff;
try { isRef(source) ? source.value : source(); } finally { activeEffect = prev; }
},
scheduler() {
const newVal = isRef(source) ? source.value : source();
if (cleanup) { cleanup(); cleanup = null; }
cb(newVal, oldVal, registerCleanup);
oldVal = newVal;
}
};
eff.run();
return () => {
if (cleanup) { cleanup(); cleanup = null; }
eff.deps.forEach(d => d.delete(eff));
};
}
window.runCompositionTests = async function () {
// Case 1: setup + ref + reactive + computed caching + readonly + utility helpers
const count = ref(0);
const doubled = computed(() => count.value * 2);
const rawObj = { label: 'init', n: 1 };
const state = reactive(rawObj);
const ro = readonly({ locked: 10 });
ro.locked = 99;
const { n: nRef } = toRefs(state);
nRef.value = 5;
const rawTagged = markRaw({ plain: true });
const counterText = document.getElementById('counter-text');
const syncDom = () => { counterText.textContent = `${count.value}/${doubled.value}`; };
document.getElementById('counter-btn').addEventListener('click', () => {
count.value += 1;
syncDom();
});
syncDom();
const d1 = doubled.value;
const d2 = doubled.value; // cached!
const computeCountBeforeClick = doubled._computeCount;
document.getElementById('counter-btn').click();
const computeCountAfterClick = doubled._computeCount;
// Case 2: Lifecycle hooks mapping + provide/inject + effectScope
const lifecycle = [];
const provided = new Map();
const provide = (k, v) => provided.set(k, v);
const inject = (k, def) => (provided.has(k) ? provided.get(k) : def);
const hooks = { onBeforeMount: [], onMounted: [], onBeforeUpdate: [], onUpdated: [], onBeforeUnmount: [], onUnmounted: [] };
// setup runs before created/mounted
lifecycle.push('setup');
provide('theme', 'sky-blue');
hooks.onBeforeMount.push(() => lifecycle.push('onBeforeMount'));
hooks.onMounted.push(() => lifecycle.push('onMounted:' + inject('theme')));
hooks.onBeforeUpdate.push(() => lifecycle.push('onBeforeUpdate'));
hooks.onUpdated.push(() => lifecycle.push('onUpdated'));
hooks.onBeforeUnmount.push(() => lifecycle.push('onBeforeUnmount'));
hooks.onUnmounted.push(() => lifecycle.push('onUnmounted'));
['onBeforeMount', 'onMounted', 'onBeforeUpdate', 'onUpdated', 'onBeforeUnmount', 'onUnmounted']
.forEach(h => hooks[h].forEach(fn => fn()));
const scopeLog = [];
const scopeVal = ref(1);
const scope = effectScope();
let currentScopeMatched = false;
scope.run(() => {
currentScopeMatched = (getCurrentScope() === scope);
watchEffect(() => { scopeLog.push('eff:' + scopeVal.value); });
onScopeDispose(() => scopeLog.push('disposed'));
});
scopeVal.value = 2;
scope.stop();
scopeVal.value = 3; // stopped, should NOT push
// Case 3: Template ref + v-for function ref with onBeforeUpdate reset
const rootRef = ref(null);
const beforeMountRefIsNull = (rootRef.value === null);
rootRef.value = document.getElementById('tpl-root');
const mountedRefTag = rootRef.value.tagName;
const listBox = document.getElementById('list-box');
let divs = [];
function renderList(items) {
divs = []; // onBeforeUpdate reset
listBox.innerHTML = '';
items.forEach((item, i) => {
const d = document.createElement('div');
d.textContent = String(item);
listBox.appendChild(d);
divs[i] = d;
});
}
renderList([1, 2, 3]);
const vforInitialTexts = divs.map(d => d.textContent);
renderList([10, 20]);
const vforUpdatedTexts = divs.map(d => d.textContent);
// Case 4: watchEffect pre vs flush:'post' on template ref + watch cleanup
const domRef = ref(null);
const preObs = [];
const postObs = [];
watchEffect(() => { preObs.push(domRef.value ? domRef.value.id : null); });
watchEffect(() => { postObs.push(domRef.value ? domRef.value.id : null); }, { flush: 'post' });
// Simulate DOM mount completing synchronously before microtask flush
domRef.value = document.getElementById('tpl-root');
await Promise.resolve();
const cleanupLog = [];
const wSrc = ref('a');
const stopWatch = watch(wSrc, (nv, ov, onCleanup) => {
cleanupLog.push(`change:${ov}->${nv}`);
onCleanup(() => cleanupLog.push(`cleanup:${nv}`));
});
wSrc.value = 'b';
wSrc.value = 'c';
stopWatch();
return {
case1: {
dom_after_click: counterText.textContent,
cached_compute_before: computeCountBeforeClick,
compute_after_click: computeCountAfterClick,
readonly_locked: ro.locked,
toRefs_synced_n: state.n,
flags: {
isRef: isRef(count),
unref: unref(count),
toValue: toValue(() => 7),
isProxy: isProxy(state),
isReactive: isReactive(state),
isReadonly: isReadonly(ro),
toRawEq: toRaw(state) === rawObj,
markRawSkipped: !isReactive(reactive(rawTagged))
}
},
case2: {
lifecycle,
scope_matched: currentScopeMatched,
scope_log: scopeLog
},
case3: {
before_mount_null: beforeMountRefIsNull,
mounted_tag: mountedRefTag,
vfor_initial: vforInitialTexts,
vfor_updated: vforUpdatedTexts
},
case4: {
pre_first_obs: preObs[0],
post_first_obs: postObs[0],
cleanup_log: cleanupLog
}
};
};
</script>
</body>
</html>
"""
def main():
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML)
out = page.evaluate("window.runCompositionTests()")
browser.close()
expected = {
"setup_ref_reactive_computed_and_readonly": {
"dom_after_click": "1/2",
"cached_compute_before": 1,
"compute_after_click": 2,
"readonly_locked": 10,
"toRefs_synced_n": 5,
"flags": {
"isRef": True,
"unref": 1,
"toValue": 7,
"isProxy": True,
"isReactive": True,
"isReadonly": True,
"toRawEq": True,
"markRawSkipped": True,
},
},
"lifecycle_hooks_and_provide_inject": {
"lifecycle": [
"setup",
"onBeforeMount",
"onMounted:sky-blue",
"onBeforeUpdate",
"onUpdated",
"onBeforeUnmount",
"onUnmounted",
],
"scope_matched": True,
"scope_log": ["eff:1", "eff:2", "disposed"],
},
"template_ref_and_v_for_function_ref": {
"before_mount_null": True,
"mounted_tag": "DIV",
"vfor_initial": ["1", "2", "3"],
"vfor_updated": ["10", "20"],
},
"watch_watchEffect_flush_post_and_cleanup": {
"pre_first_obs": None,
"post_first_obs": "tpl-root",
"cleanup_log": ["change:a->b", "cleanup:b", "change:b->c", "cleanup:c"],
},
}
mapping = [
("setup_ref_reactive_computed_and_readonly", out["case1"]),
("lifecycle_hooks_and_provide_inject", out["case2"]),
("template_ref_and_v_for_function_ref", out["case3"]),
("watch_watchEffect_flush_post_and_cleanup", out["case4"]),
]
cases = [
{"name": name, "expected": expected[name], "actual": actual, "passed": actual == expected[name]}
for name, actual in mapping
]
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
watchEffect 默认在 DOM 挂载与更新前(flush: 'pre')执行,首次运行时模板尚未挂载,因此 root.value 为 null;传入 { flush: 'post' } 或改用 watchPostEffect() 即可确保在 DOM 更新后读取真实元素。