蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 验证 Object.defineProperty、Vue.set 与 Vue.delete

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-vuejs-reactive.py
explore-vuejs-reactive.py188 行
"""Offline Chromium runtime verification for Vue 2 Chapter 21: vuejs-reactive."""
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")


def make_case(name, expected, actual):
    return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()

        page.set_content("""
        <!doctype html>
        <html><body>
          <p id="counter-p">计数器: 1</p>
          <button id="inc-btn">点我</button>
          <p id="qty-p"></p>
          <script>
            function defineReactive(obj, key, val, notify) {
              Object.defineProperty(obj, key, {
                enumerable: true,
                configurable: true,
                get() { return val; },
                set(newVal) {
                  if (newVal === val) return;
                  const oldVal = val;
                  val = newVal;
                  notify(key, newVal, oldVal);
                }
              });
            }
            function makeObservable(raw) {
              const listeners = [];
              const notify = (key, nv, ov) => listeners.forEach(fn => fn(key, nv, ov));
              Object.keys(raw).forEach(k => defineReactive(raw, k, raw[k], notify));
              Object.defineProperty(raw, '__ob__', {
                enumerable: false,
                value: { listeners, notify }
              });
              return raw;
            }
            function VueSet(target, key, val) {
              if (Array.isArray(target)) {
                target.splice(key, 1, val);
                return val;
              }
              const ob = target.__ob__;
              defineReactive(target, key, val, ob.notify);
              ob.notify(key, val, undefined);
              return val;
            }
            function VueDelete(target, key) {
              if (!Object.prototype.hasOwnProperty.call(target, key)) return;
              const oldVal = target[key];
              delete target[key];
              target.__ob__.notify(key, undefined, oldVal);
            }

            // Case 1: $watch + click + delayed update
            const vmData = makeObservable({ counter: 1 });
            const watchLogs = [];
            vmData.__ob__.listeners.push((k, nv, ov) => {
              if (k === 'counter') {
                watchLogs.push(`${ov}->${nv}`);
                document.getElementById('counter-p').textContent = `计数器: ${nv}`;
              }
            });
            document.getElementById('inc-btn').addEventListener('click', () => { vmData.counter += 1; });
            window.__runCase1Delay = () => new Promise(resolve => {
              setTimeout(() => {
                vmData.counter += 20;
                resolve({
                  watchLogs,
                  counter: vmData.counter,
                  domText: document.getElementById('counter-p').textContent,
                });
              }, 30);
            });

            // Case 2: direct property assignment lacks getter/setter and does not notify
            const p1 = makeObservable({ id: 1, name: 'book', price: '20.00' });
            let p1Notifications = 0;
            p1.__ob__.listeners.push(() => { p1Notifications += 1; });
            p1.qty = '1';
            p1.qty = '2';
            const hasAccessor = (obj, k) => {
              const d = Object.getOwnPropertyDescriptor(obj, k);
              return Boolean(d && typeof d.get === 'function' && typeof d.set === 'function');
            };
            window.__case2 = {
              idReactive: hasAccessor(p1, 'id'),
              nameReactive: hasAccessor(p1, 'name'),
              priceReactive: hasAccessor(p1, 'price'),
              qtyReactive: hasAccessor(p1, 'qty'),
              qtyValue: p1.qty,
              notificationsTriggered: p1Notifications,
            };

            // Case 3: Vue.set installs getter/setter and triggers reactivity
            const p2 = makeObservable({ id: 1, name: 'book', price: '20.00' });
            const p2Logs = [];
            p2.__ob__.listeners.push((k, nv, ov) => {
              p2Logs.push({ key: k, old: ov === undefined ? null : ov, next: nv });
              if (k === 'qty') document.getElementById('qty-p').textContent = 'qty=' + nv;
            });
            VueSet(p2, 'qty', 1);
            p2.qty = 5;
            window.__case3 = {
              qtyReactiveAfterSet: hasAccessor(p2, 'qty'),
              logs: p2Logs,
              domQtyText: document.getElementById('qty-p').textContent,
            };

            // Case 4: Vue.delete removes property and notifies watchers
            const p3 = makeObservable({ id: 1, name: 'book', price: '20.00' });
            const p3Logs = [];
            p3.__ob__.listeners.push((k, nv, ov) => {
              p3Logs.push({ key: k, deletedOld: ov });
            });
            VueDelete(p3, 'price');
            window.__case4 = {
              hasPrice: 'price' in p3,
              priceDescriptorExists: Object.getOwnPropertyDescriptor(p3, 'price') !== undefined,
              remainingKeys: Object.keys(p3),
              deleteNotifications: p3Logs,
            };
          </script>
        </body></html>
        """)

        page.click("#inc-btn")
        actual1 = page.evaluate("window.__runCase1Delay()")
        cases.append(make_case(
            "watch_and_delayed_update",
            {"watchLogs": ["1->2", "2->22"], "counter": 22, "domText": "计数器: 22"},
            actual1,
        ))
        cases.append(make_case(
            "direct_add_property_not_reactive",
            {
                "idReactive": True,
                "nameReactive": True,
                "priceReactive": True,
                "qtyReactive": False,
                "qtyValue": "2",
                "notificationsTriggered": 0,
            },
            page.evaluate("window.__case2"),
        ))
        cases.append(make_case(
            "vue_set_makes_property_reactive",
            {
                "qtyReactiveAfterSet": True,
                "logs": [{"key": "qty", "old": None, "next": 1}, {"key": "qty", "old": 1, "next": 5}],
                "domQtyText": "qty=5",
            },
            page.evaluate("window.__case3"),
        ))
        cases.append(make_case(
            "vue_delete_removes_property_and_notifies",
            {
                "hasPrice": False,
                "priceDescriptorExists": False,
                "remainingKeys": ["id", "name"],
                "deleteNotifications": [{"key": "price", "deletedOld": "20.00"}],
            },
            page.evaluate("window.__case4"),
        ))

        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-vuejs-reactive-lab/explore-vuejs-reactive.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-vuejs-reactive.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Vue.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a798.zip

下载课程关联工程包:Vue.js

课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习