"""Offline Playwright Chromium lab for Vue 2 Chapter 09 (vue-watch)."""
import json
from playwright.sync_api import sync_playwright
MINI_VUE2_WATCH_JS = r"""
(function (global) {
class Dep {
constructor() { this.subs = new Set(); }
depend() { if (Dep.target) this.subs.add(Dep.target); }
notify() { Array.from(this.subs).forEach(w => w.update()); }
}
Dep.target = null;
class Watcher {
constructor(vm, getter, cb) {
this.vm = vm;
this.getter = getter;
this.cb = cb;
this.value = this.get();
}
get() {
Dep.target = this;
const v = this.getter.call(this.vm);
Dep.target = null;
return v;
}
update() {
const oldVal = this.value;
const newVal = this.get();
if (newVal === oldVal) return;
this.value = newVal;
if (this.cb) this.cb.call(this.vm, newVal, oldVal);
}
}
function observe(data) {
Object.keys(data).forEach(key => {
let val = data[key];
const dep = new Dep();
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get() { dep.depend(); return val; },
set(newVal) {
if (newVal === val) return;
val = newVal;
dep.notify();
}
});
});
}
function evalExpr(vm, expr) {
return new Function('with(this){ return (' + expr + '); }').call(vm);
}
class Vue {
constructor(options) {
this.$options = options || {};
this.$data = options.data || {};
observe(this.$data);
Object.keys(this.$data).forEach(k => {
Object.defineProperty(this, k, {
enumerable: true,
configurable: true,
get: () => this.$data[k],
set: (v) => { this.$data[k] = v; }
});
});
this.$el = document.querySelector(options.el);
if (this.$el) this._compile(this.$el);
const watches = options.watch || {};
Object.keys(watches).forEach(k => {
this.$watch(k, watches[k]);
});
}
$watch(key, cb) {
return new Watcher(this, () => this[key], cb);
}
_compile(node) {
Array.from(node.childNodes).forEach(child => {
if (child.nodeType === 3 && /\{\{(.+?)\}\}/.test(child.textContent)) {
const tpl = child.textContent;
const render = () => tpl.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalExpr(this, exp.trim()));
const w = new Watcher(this, render, v => { child.textContent = v; });
child.textContent = w.value;
} else if (child.nodeType === 1) {
Array.from(child.attributes).forEach(attr => {
if (attr.name === 'v-model') {
const prop = attr.value.trim();
child.removeAttribute('v-model');
const w = new Watcher(this, () => this[prop], v => { child.value = String(v); });
child.value = String(w.value);
child.addEventListener('input', () => {
const n = Number(child.value);
this[prop] = Number.isNaN(n) || child.value.trim() === '' ? child.value : n;
});
} else if (attr.name === '@click' || attr.name === 'v-on:click') {
const stmt = attr.value.trim();
child.removeAttribute(attr.name);
child.addEventListener('click', () => {
new Function('with(this){ ' + stmt + ' }').call(this);
});
}
});
this._compile(child);
}
});
}
}
global.Vue = Vue;
})(window);
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue 2 监听属性 watch 实验</title></head>
<body>
<div id="app">
<p id="counter-text">计数器: {{{{ counter }}}}</p>
<button id="btn-inc" type="button" @click="counter++">点我</button>
</div>
<div id="computed_props">
千米: <input id="km-input" type="text" v-model="kilometers">
米: <input id="m-input" type="text" v-model="meters">
</div>
<p id="info"></p>
<script>{MINI_VUE2_WATCH_JS}</script>
<script>
window.counterLogs = [];
window.watchTriggerCount = 0;
window.vmCounter = new Vue({{
el: '#app',
data: {{ counter: 1 }}
}});
window.vmCounter.$watch('counter', function (nval, oval) {{
window.counterLogs.push(oval + '->' + nval);
}});
window.vmUnit = new Vue({{
el: '#computed_props',
data: {{ kilometers: 0, meters: 0 }},
watch: {{
kilometers: function (val) {{
window.watchTriggerCount += 1;
this.kilometers = val;
this.meters = this.kilometers * 1000;
}},
meters: function (val) {{
window.watchTriggerCount += 1;
this.kilometers = val / 1000;
this.meters = val;
}}
}}
}});
window.vmUnit.$watch('kilometers', function (newValue, oldValue) {{
document.getElementById('info').textContent = '修改前值为: ' + oldValue + ',修改后值为: ' + newValue;
}});
</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()
page.set_content(HTML_DOC)
# Case 1: vm.$watch observing counter clicks
page.click("#btn-inc")
page.click("#btn-inc")
page.click("#btn-inc")
res1 = page.evaluate("""() => ({
counter_dom: document.getElementById('counter-text').textContent,
counter_val: window.vmCounter.counter,
watch_logs: window.counterLogs
})""")
exp1 = {
"counter_dom": "计数器: 4",
"counter_val": 4,
"watch_logs": ["1->2", "2->3", "3->4"],
}
cases.append({
"name": "dollar_watch_counter_clicks",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: watch kilometers -> meters conversion + $watch info banner
page.fill("#km-input", "2.5")
res2 = page.evaluate("""() => ({
km: window.vmUnit.kilometers,
meters: window.vmUnit.meters,
meters_input_val: document.getElementById('m-input').value,
info_text: document.getElementById('info').textContent
})""")
exp2 = {
"km": 2.5,
"meters": 2500,
"meters_input_val": "2500",
"info_text": "修改前值为: 0,修改后值为: 2.5",
}
cases.append({
"name": "watch_km_to_meters_conversion",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: watch meters -> kilometers conversion + finite convergence guard
triggers_before = page.evaluate("() => window.watchTriggerCount")
page.fill("#m-input", "1750")
res3 = page.evaluate("""(before) => ({
km: window.vmUnit.kilometers,
meters: window.vmUnit.meters,
km_input_val: document.getElementById('km-input').value,
info_text: document.getElementById('info').textContent,
triggers_added: window.watchTriggerCount - before
})""", triggers_before)
exp3 = {
"km": 1.75,
"meters": 1750,
"km_input_val": "1.75",
"info_text": "修改前值为: 2.5,修改后值为: 1.75",
"triggers_added": 2,
}
cases.append({
"name": "watch_meters_to_km_and_guard",
"passed": res3 == exp3,
"expected": exp3,
"actual": res3,
})
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/vue2-vue-watch-lab/explore-vue-watch.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-vue-watch.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a795.zip
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip