Vue.js 监听属性
核对 Vue 2 侦听器 watch 选项与 vm.$watch 实例方法在计数器变化追踪、千米/米双向换算联动及等值防递归收敛中的离线 Chromium 实测表现。
学完这一章,你能够
- 核对 Vue 2 侦听器 watch 选项与 vm.$watch 实例方法在计数器变化追踪、千米/米双向换算联动及等值防递归收敛中的离线 Chromium 实测表现。
使用 vm.$watch 监听数据变化
Vue 提供侦听属性 `watch` 选项以及实例方法 `vm.$watch(key, callback)`,用于在指定响应式数据发生变化时执行回调逻辑(回调签名接收 `(newValue, oldValue)` 两个参数),适合触发日志记录、异步请求或跨字段副作用。以计数器为例,点击按钮执行 `@click="counter++"` 递增 `counter` 时,注册的 `vm.$watch('counter', ...)` 会在每次数值变更后收到旧值与新值。本站离线 Chromium 真实点击按钮 3 次实测:`counter` 视图由 `1` 递增至 `计数器: 4`,侦听回调按序记录 `['1->2', '2->3', '3->4']`。
watch 选项实现千米与米双向联动换算
当两个输入字段需要互相换算时,可在 `data` 中初始化 `kilometers: 0` 与 `meters: 0`,并在 `watch` 选项中分别监听 `kilometers`(将 `meters` 设为 `kilometers * 1000`)和 `meters`(将 `kilometers` 设为 `meters / 1000`),同时配合 `vm.$watch('kilometers', ...)` 把修改前后的值渲染到 `#info` 提示区。本站离线 Chromium 真实输入实测:先向千米框填入 `2.5`,米框立即联动变为 `2500`,`#info` 显示 `修改前值为: 0,修改后值为: 2.5`;再向米框填入 `1750`,千米框同步换算为 `1.75`,`#info` 更新为 `修改前值为: 2.5,修改后值为: 1.75`,且由于第二次回写产生的新值与当前值相等不再派发通知,双向监听仅新增 `2` 次回调即稳定收敛、不会陷入死循环(来源页面的演示视频标签仅作结构留证,交互效果已由上述实测独立验证)。
离线 Chromium 核验 vm.$watch 计数器追踪与千米/米双向 watch 联动收敛
"""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()
- 核对点击 3 次后计数器显示 4 且日志为 ['1->2','2->3','3->4'],输入 2.5 千米联动 2500 米、输入 1750 米联动 1.75 千米且仅新增 2 次回调即收敛。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:e665c5fa0a7e1f04295e07f4300620f9bd4c48969200286529822bdd1b636c8d
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:0d1b1f40da93f8f34a9b27321f996ee8910d3db9352c4952b5e1259516cc0379
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么在千米与米互相监听的示例中,`meters` 回调修改 `kilometers` 进而触发 `kilometers` 回调回写 `meters` 后,不会造成无限死循环?
展开参考解答
因为 Vue 的响应式 setter 与 Watcher 在赋值时会比较新旧值:当 `kilometers` 回调算出相同的 `meters` 数值并回写时,新值与当前值严格相等,不会再次触发依赖通知,监听链随之终止。