"""Offline Playwright Chromium lab for Vue 3 Ch 45: watch, watchEffect, debounce & real-time search."""
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>BlueSky Blog</title>
<style>
.filter-bar button.active { background: #42b883; color: #fff; }
mark { background: #fff3b0; }
</style>
</head>
<body>
<section id="search-app">
<div class="search-bar">
<input id="search-input" type="text" placeholder="搜索文章标题或摘要...">
<button id="clear-btn" style="display:none">✕</button>
</div>
<div id="category-bar" class="filter-bar"></div>
<p id="status-tip"></p>
<div id="article-grid"></div>
</section>
<section id="debounce-box">
<input id="debounce-input" type="text">
<div id="debounce-result"></div>
</section>
<script>
// Minimal reactive + watch + watchEffect runtime
let activeEffect = null;
const deps = new WeakMap();
function track(t, k) {
if (!activeEffect) return;
let m = deps.get(t);
if (!m) deps.set(t, (m = new Map()));
let s = m.get(k);
if (!s) m.set(k, (s = new Set()));
s.add(activeEffect);
}
function trigger(t, k) {
const m = deps.get(t);
if (!m) return;
const s = m.get(k);
if (s) [...s].forEach((fn) => { if (fn !== activeEffect) fn(); });
}
function ref(val) {
const r = {
__isRef: true,
get value() { track(r, 'value'); return val; },
set value(v) { if (!Object.is(val, v)) { val = v; trigger(r, 'value'); } }
};
return r;
}
function reactive(obj) {
return new Proxy(obj, {
get(t, k, rec) { track(t, k); return Reflect.get(t, k, rec); },
set(t, k, v, rec) { const ok = Reflect.set(t, k, v, rec); trigger(t, k); return ok; }
});
}
function watchEffect(fn) {
const runner = () => {
activeEffect = runner;
try { fn(); } finally { activeEffect = null; }
};
runner();
return runner;
}
function readSource(src) {
if (Array.isArray(src)) return src.map(readSource);
if (typeof src === 'function') return src();
if (src && src.__isRef) return src.value;
return src;
}
function watch(source, cb, options = {}) {
let oldVal;
let initialized = false;
const runner = () => {
activeEffect = runner;
let newVal;
try { newVal = readSource(source); } finally { activeEffect = null; }
if (!initialized) {
initialized = true;
if (options.immediate) cb(newVal, undefined);
oldVal = Array.isArray(newVal) ? [...newVal] : newVal;
return;
}
cb(newVal, oldVal);
oldVal = Array.isArray(newVal) ? [...newVal] : newVal;
};
runner();
}
// === Case 1: watch single ref, reactive getter, multi-source, lazy vs immediate ===
const kw1 = ref('');
const cat1 = ref('全部');
const user = reactive({ name: '小明' });
const watchLogs = { single: [], immediate: [], getter: [], multi: [] };
watch(kw1, (n, o) => {
watchLogs.single.push([o, n]);
document.title = n ? `搜索:${n}` : 'BlueSky Blog';
});
watch(kw1, (n, o) => {
watchLogs.immediate.push([o === undefined ? null : o, n]);
}, { immediate: true });
watch(() => user.name, (n, o) => {
watchLogs.getter.push([o, n]);
});
watch([kw1, cat1], ([nk, nc], [ok, oc]) => {
watchLogs.multi.push([[ok, oc], [nk, nc]]);
});
const lazyInitialHits = watchLogs.single.length;
const immediateInitialHits = watchLogs.immediate.length;
// === Case 2: watchEffect auto-tracking & immediate execution ===
const effKeyword = ref('');
const miniPosts = ref([
{ id: 1, title: 'Vue3 入门' },
{ id: 2, title: 'JS 异步' }
]);
const effFiltered = ref([]);
const effCounts = [];
watchEffect(() => {
effFiltered.value = miniPosts.value.filter((a) => a.title.includes(effKeyword.value));
effCounts.push(effFiltered.value.length);
});
// === Case 3: Debounced watch coalescing rapid inputs + highlight ===
const articles = [
{ id: 1, title: 'Vue3 入门完全指南', summary: '从零开始学习 Vue3 组合式 API', category: 'Vue' },
{ id: 2, title: 'JS 异步编程详解', summary: '搞懂 Promise 和 async/await', category: 'JavaScript' },
{ id: 3, title: 'CSS Grid 布局实战', summary: '用 Grid 实现响应式布局', category: 'CSS' },
{ id: 4, title: 'Vue3 响应式原理', summary: '深入理解 ref 和 reactive 与异步更新', category: 'Vue' }
];
const debKeyword = ref('');
let debTimer = null;
let debRuns = 0;
let debLastMatched = [];
watch(debKeyword, (newVal) => {
clearTimeout(debTimer);
debTimer = setTimeout(() => {
debRuns++;
const q = newVal.trim().toLowerCase();
debLastMatched = articles
.filter((a) => !q || a.title.toLowerCase().includes(q) || a.summary.toLowerCase().includes(q))
.map((a) => a.title);
const box = document.getElementById('debounce-result');
box.innerHTML = debLastMatched
.map((t) => `<p>${q ? t.replace(new RegExp(newVal.trim(), 'gi'), (m) => `<mark>${m}</mark>`) : t}</p>`)
.join('');
}, 180);
});
document.getElementById('debounce-input').addEventListener('input', (e) => {
debKeyword.value = e.target.value;
});
// === Case 4: Blog real-time search + category combined filter ===
const searchKeyword = ref('');
const activeCategory = ref('全部');
const categories = ['全部', ...new Set(articles.map((a) => a.category))];
function renderBlogSearch() {
const bar = document.getElementById('category-bar');
bar.innerHTML = '';
for (const c of categories) {
const btn = document.createElement('button');
btn.textContent = c;
btn.dataset.cat = c;
if (activeCategory.value === c) btn.className = 'active';
btn.addEventListener('click', () => {
activeCategory.value = c;
renderBlogSearch();
});
bar.appendChild(btn);
}
const clearBtn = document.getElementById('clear-btn');
clearBtn.style.display = searchKeyword.value ? 'inline-block' : 'none';
let result = articles;
if (activeCategory.value !== '全部') {
result = result.filter((a) => a.category === activeCategory.value);
}
const kw = searchKeyword.value.trim().toLowerCase();
if (kw) {
result = result.filter(
(a) => a.title.toLowerCase().includes(kw) || a.summary.toLowerCase().includes(kw)
);
}
const tip = document.getElementById('status-tip');
const grid = document.getElementById('article-grid');
if (result.length === 0) {
tip.textContent = '没有找到匹配的文章';
grid.innerHTML = '';
} else {
tip.textContent = `找到 ${result.length} 篇`;
grid.innerHTML = result.map((a) => `<div class="card"><h3>${a.title}</h3></div>`).join('');
}
}
document.getElementById('search-input').addEventListener('input', (e) => {
searchKeyword.value = e.target.value;
renderBlogSearch();
});
document.getElementById('clear-btn').addEventListener('click', () => {
searchKeyword.value = '';
document.getElementById('search-input').value = '';
renderBlogSearch();
});
renderBlogSearch();
window.__watchLab = {
runWatchScenarios() {
kw1.value = 'Vue';
const titleAfterVue = document.title;
user.name = '小华';
cat1.value = 'CSS';
return {
lazyInitialHits,
immediateInitialHits,
titleAfterVue,
watchLogs
};
},
runWatchEffectScenario() {
effKeyword.value = 'Vue3';
const afterVue = effFiltered.value.map((a) => a.title);
effKeyword.value = '';
return { effCounts, afterVue };
},
getDebounceReport() {
return { debRuns, debLastMatched };
}
};
</script>
</body>
</html>
"""
def main():
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
page.set_content(HTML)
# Case 1: watch single, getter, multi, lazy vs immediate
w_rep = page.evaluate("window.__watchLab.runWatchScenarios()")
# Case 2: watchEffect immediate & auto-tracking
we_rep = page.evaluate("window.__watchLab.runWatchEffectScenario()")
# Case 3: Debounced watch coalescing 3 rapid inputs into 1 execution + <mark>
page.evaluate("""() => {
const inp = document.getElementById('debounce-input');
for (const v of ['V', 'Vu', 'Vue3']) {
inp.value = v;
inp.dispatchEvent(new Event('input', { bubbles: true }));
}
}""")
page.wait_for_timeout(260)
deb_rep = page.evaluate("window.__watchLab.getDebounceReport()")
mark_texts = page.eval_on_selector_all("#debounce-result mark", "els => els.map(e => e.textContent)")
# Case 4: Blog combined search + category filter + clear button + empty state
page.fill("#search-input", "异步")
async_titles = page.eval_on_selector_all("#article-grid .card h3", "els => els.map(e => e.textContent)")
page.click('#category-bar button[data-cat="Vue"]')
combined_titles = page.eval_on_selector_all("#article-grid .card h3", "els => els.map(e => e.textContent)")
page.click("#clear-btn")
after_clear_titles = page.eval_on_selector_all("#article-grid .card h3", "els => els.map(e => e.textContent)")
page.fill("#search-input", "Rust不存在")
empty_tip = page.text_content("#status-tip")
finally:
browser.close()
actuals = {
"watch_single_getter_multi_and_immediate": {
"lazy_initial_hits": w_rep["lazyInitialHits"],
"immediate_initial_hits": w_rep["immediateInitialHits"],
"title_after_vue": w_rep["titleAfterVue"],
"single_log": w_rep["watchLogs"]["single"],
"getter_log": w_rep["watchLogs"]["getter"],
"multi_log": w_rep["watchLogs"]["multi"],
},
"watch_effect_immediate_auto_track": {
"counts": we_rep["effCounts"],
"after_vue": we_rep["afterVue"],
},
"debounced_watch_coalesces_rapid_input": {
"debounce_runs": deb_rep["debRuns"],
"matched_titles": deb_rep["debLastMatched"],
"highlighted_marks": mark_texts,
},
"blog_search_and_category_combined_dom": {
"async_all_categories": async_titles,
"async_and_vue": combined_titles,
"after_clear_vue_only": after_clear_titles,
"empty_tip": empty_tip,
},
}
expected = {
"watch_single_getter_multi_and_immediate": {
"lazy_initial_hits": 0,
"immediate_initial_hits": 1,
"title_after_vue": "搜索:Vue",
"single_log": [["", "Vue"]],
"getter_log": [["小明", "小华"]],
"multi_log": [[["", "全部"], ["Vue", "全部"]], [["Vue", "全部"], ["Vue", "CSS"]]],
},
"watch_effect_immediate_auto_track": {
"counts": [2, 1, 2],
"after_vue": ["Vue3 入门"],
},
"debounced_watch_coalesces_rapid_input": {
"debounce_runs": 1,
"matched_titles": ["Vue3 入门完全指南", "Vue3 响应式原理"],
"highlighted_marks": ["Vue3", "Vue3"],
},
"blog_search_and_category_combined_dom": {
"async_all_categories": ["JS 异步编程详解", "Vue3 响应式原理"],
"async_and_vue": ["Vue3 响应式原理"],
"after_clear_vue_only": ["Vue3 入门完全指南", "Vue3 响应式原理"],
"empty_tip": "没有找到匹配的文章",
},
}
cases = [
{"name": k, "expected": expected[k], "actual": actuals[k], "passed": actuals[k] == expected[k]}
for k in expected
]
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vue3-blog-watch-search-lab/explore-blog-watch-search.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-watch-search.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a810.zip