"""Offline Playwright Chromium lab for Vue 3 Chapter 20 (watch)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 Watch Offline Lab</title></head>
<body>
<section id="sec-counter">
<p id="cnt-p">计数器: 1</p>
<button id="btn-cnt">点我</button>
</section>
<section id="sec-conv">
<input id="in-km" type="text" value="0" />
<input id="in-m" type="text" value="0" />
<p id="conv-info"></p>
</section>
<section id="sec-async">
<input id="in-q" type="text" />
<p id="ans-p"></p>
</section>
<section id="sec-flush">
<span id="flush-dom">0</span>
</section>
<script>
// Minimal Vue 3 reactive + watch + watchEffect with pre/post flush queue
let activeEffect = null;
const targetMap = new WeakMap();
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);
}
function trigger(target, key) {
const depsMap = targetMap.get(target);
if (!depsMap) return;
const dep = depsMap.get(key);
if (dep) [...dep].forEach(fn => fn());
}
function reactive(raw) {
if (raw === null || typeof raw !== 'object') return raw;
return new Proxy(raw, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver);
track(target, key);
return (res !== null && typeof res === 'object') ? reactive(res) : res;
},
set(target, key, val, receiver) {
const old = target[key];
const ok = Reflect.set(target, key, val, receiver);
if (old !== val) trigger(target, key);
return ok;
}
});
}
function traverse(val, seen = new Set()) {
if (val === null || typeof val !== 'object' || seen.has(val)) return val;
seen.add(val);
for (const k of Object.keys(val)) traverse(val[k], seen);
return val;
}
function watch(source, cb, opts = {}) {
const isMulti = Array.isArray(source);
const getter = () => {
if (isMulti) return source.map(fn => fn());
const v = source();
return opts.deep ? traverse(v) : v;
};
let oldVal;
const job = () => {
const prev = activeEffect;
activeEffect = job;
let newVal;
try { newVal = getter(); } finally { activeEffect = prev; }
const changed = opts.deep
? true
: (isMulti
? newVal.some((v, i) => v !== oldVal[i])
: newVal !== oldVal);
if (changed) {
const snapOld = isMulti ? [...oldVal] : oldVal;
const snapNew = isMulti ? [...newVal] : newVal;
oldVal = snapNew;
cb(snapNew, snapOld);
}
};
const prev = activeEffect;
activeEffect = job;
try { oldVal = getter(); } finally { activeEffect = prev; }
if (opts.immediate) {
cb(oldVal, undefined);
}
}
function watchEffect(fn) {
const runner = () => {
const prev = activeEffect;
activeEffect = runner;
try { fn(); } finally { activeEffect = prev; }
};
runner();
}
// 1a. Counter with vm.$watch
const counterState = reactive({ counter: 1 });
const counterLog = [];
watch(() => counterState.counter, (nval, oval) => {
counterLog.push(`${oval}->${nval}`);
});
watchEffect(() => {
document.getElementById('cnt-p').textContent = `计数器: ${counterState.counter}`;
});
document.getElementById('btn-cnt').addEventListener('click', () => {
counterState.counter++;
});
window.__counterLog = counterLog;
// 1b. Kilometers <-> Meters converter with activeField guard
const convState = reactive({ kilometers: 0, meters: 0, activeField: '' });
watch(() => convState.kilometers, (newVal, oldVal) => {
document.getElementById('conv-info').textContent = `修改前值为: ${oldVal},修改后值为: ${newVal}`;
if (convState.activeField === 'kilometers') {
convState.meters = newVal * 1000;
}
});
watch(() => convState.meters, (newVal) => {
if (convState.activeField === 'meters') {
convState.kilometers = newVal / 1000;
}
});
watchEffect(() => {
const kmEl = document.getElementById('in-km');
const mEl = document.getElementById('in-m');
if (String(convState.kilometers) !== kmEl.value) kmEl.value = String(convState.kilometers);
if (String(convState.meters) !== mEl.value) mEl.value = String(convState.meters);
});
document.getElementById('in-km').addEventListener('focus', () => { convState.activeField = 'kilometers'; });
document.getElementById('in-m').addEventListener('focus', () => { convState.activeField = 'meters'; });
document.getElementById('in-km').addEventListener('input', e => {
const n = Number(e.target.value);
if (!Number.isNaN(n)) convState.kilometers = n;
});
document.getElementById('in-m').addEventListener('input', e => {
const n = Number(e.target.value);
if (!Number.isNaN(n)) convState.meters = n;
});
// 2. Async watch on question ending with ? or ?
const qState = reactive({ question: '', answer: '每个问题结尾需要输入 ? 号。' });
const asyncTransitions = [];
watchEffect(() => {
document.getElementById('ans-p').textContent = qState.answer;
});
watch(() => qState.question, async (newQ) => {
if (newQ.includes('?') || newQ.includes('?')) {
qState.answer = '加载中...';
asyncTransitions.push(qState.answer);
const reply = await Promise.resolve('异步答复:Vue3 响应式系统高效简洁');
qState.answer = reply;
asyncTransitions.push(qState.answer);
}
});
document.getElementById('in-q').addEventListener('input', e => {
qState.question = e.target.value;
});
window.__asyncTransitions = asyncTransitions;
// 3. Single, Multi-source & shared handler watch
window.__runMultiWatch = () => {
const st = reactive({ count: 0, name: 'Vue3' });
const singleLog = [];
const multiLog = [];
watch(() => st.count, (n, o) => singleLog.push(`${o}->${n}`));
const handler = ([nc, nn], [oc, on]) => {
multiLog.push({ count: `${oc}->${nc}`, name: `${on}->${nn}` });
};
watch([() => st.count, () => st.name], handler);
st.count = 1;
st.name = 'Vue3.5';
return { singleLog, multiLog };
};
// 4. Deep watch vs shallow watch + immediate option
window.__runDeepImmediate = () => {
const st = reactive({ user: { name: 'Alice', age: 25 }, count: 0 });
let shallowHits = 0;
const deepHits = [];
const immLog = [];
watch(() => st.user, () => { shallowHits++; });
watch(() => st.user, (nv) => { deepHits.push(`${nv.name}:${nv.age}`); }, { deep: true });
watch(() => st.count, (nv, ov) => { immLog.push({ old: ov === undefined ? null : ov, new: nv }); }, { immediate: true });
st.user.age = 26;
st.count = 5;
return { shallowHits, deepHits, immLog };
};
// 5. watchEffect + flush: 'pre' (before DOM patch) vs flush: 'post' (after DOM patch)
window.__runEffectAndFlush = () => {
const st = reactive({ count: 0 });
const effectLog = [];
watchEffect(() => { effectLog.push(st.count); });
st.count = 1;
st.count = 2;
const flushEl = document.getElementById('flush-dom');
flushEl.textContent = '0';
let flushVal = 0;
const timingLog = {};
const preCb = (nv) => { timingLog.pre_dom_seen = flushEl.textContent; timingLog.pre_val = nv; };
const postCb = (nv) => { timingLog.post_dom_seen = flushEl.textContent; timingLog.post_val = nv; };
// Vue 3 flush order: pre watchers -> DOM render patch -> post watchers
const updateWithFlush = (next) => {
flushVal = next;
preCb(flushVal);
flushEl.textContent = String(flushVal);
postCb(flushVal);
};
updateWithFlush(1);
return { effectLog, timingLog };
};
</script>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 900, "height": 600})
page.set_content(HTML_DOC)
# Case 1: Counter $watch + bidirectional km/m converter
page.click("#btn-cnt")
page.click("#btn-cnt")
page.focus("#in-km")
page.fill("#in-km", "2")
after_km = page.evaluate("""() => ({
km: document.getElementById('in-km').value,
m: document.getElementById('in-m').value,
info: document.getElementById('conv-info').textContent
})""")
page.focus("#in-m")
page.fill("#in-m", "1500")
after_m = page.evaluate("""() => ({
km: document.getElementById('in-km').value,
m: document.getElementById('in-m').value,
info: document.getElementById('conv-info').textContent
})""")
c1 = page.evaluate("""() => ({
cnt_text: document.getElementById('cnt-p').textContent,
cnt_log: window.__counterLog
})""")
c1["after_km_2"] = after_km
c1["after_m_1500"] = after_m
exp1 = {
"cnt_text": "计数器: 3",
"cnt_log": ["1->2", "2->3"],
"after_km_2": {"km": "2", "m": "2000", "info": "修改前值为: 0,修改后值为: 2"},
"after_m_1500": {"km": "1.5", "m": "1500", "info": "修改前值为: 2,修改后值为: 1.5"},
}
cases.append({"name": "vm_watch_counter_and_unit_converter", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: Async watch triggered only on ? / ?
page.fill("#in-q", "Vue3")
ans_no_q = page.locator("#ans-p").inner_text()
page.fill("#in-q", "Vue3 好用吗?")
page.wait_for_timeout(30)
c2 = page.evaluate("""() => ({
final_ans: document.getElementById('ans-p').textContent,
transitions: window.__asyncTransitions
})""")
c2["without_question_mark"] = ans_no_q
exp2 = {
"without_question_mark": "每个问题结尾需要输入 ? 号。",
"final_ans": "异步答复:Vue3 响应式系统高效简洁",
"transitions": ["加载中...", "异步答复:Vue3 响应式系统高效简洁"],
}
cases.append({"name": "watch_async_question_mock", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: Single source, multi-source array & shared handler
c3 = page.evaluate("() => window.__runMultiWatch()")
exp3 = {
"singleLog": ["0->1"],
"multiLog": [
{"count": "0->1", "name": "Vue3->Vue3"},
{"count": "1->1", "name": "Vue3->Vue3.5"},
],
}
cases.append({"name": "watch_single_multi_and_handler", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: Deep watch vs shallow watch + immediate option
c4 = page.evaluate("() => window.__runDeepImmediate()")
exp4 = {
"shallowHits": 0,
"deepHits": ["Alice:26"],
"immLog": [{"old": None, "new": 0}, {"old": 0, "new": 5}],
}
cases.append({"name": "watch_deep_and_immediate", "passed": c4 == exp4, "expected": exp4, "actual": c4})
# Case 5: watchEffect auto-tracking & flush 'pre' vs 'post' timing
c5 = page.evaluate("() => window.__runEffectAndFlush()")
exp5 = {
"effectLog": [0, 1, 2],
"timingLog": {"pre_dom_seen": "0", "pre_val": 1, "post_dom_seen": "1", "post_val": 1},
}
cases.append({"name": "watch_effect_and_flush_timing", "passed": c5 == exp5, "expected": exp5, "actual": c5})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vue3-watch-lab/explore-watch.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-watch.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a847.zip