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

在无头 Chromium 中离线验证声明式挂载、指令绑定、双向同步与虚拟 DOM 最小补丁

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial.py
explore-tutorial.py242 行
"""Offline Playwright Chromium verification for Vue 3 Ch01 (tutorial)."""
import json
from playwright.sync_api import sync_playwright


def launch_browser(p):
    for kwargs in (
        dict(headless=True),
        dict(headless=True, channel="chrome"),
        dict(headless=True, channel="msedge"),
    ):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def case_declarative_hello_mount(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"><title>Vue3 Hello</title></head>
<body>
  <div id="hello-vue" class="demo">{{ message }}</div>
  <script>
    function createMiniApp(options) {
      const listeners = new Set();
      const raw = options.data();
      const state = new Proxy(raw, {
        set(target, prop, value) {
          target[prop] = value;
          listeners.forEach((fn) => fn());
          return true;
        }
      });
      return {
        state,
        mount(selector) {
          const el = document.querySelector(selector);
          const tpl = el.textContent;
          const render = () => {
            el.textContent = tpl.replace(/\\{\\{\\s*(\\w+)\\s*\\}\\}/g, (_, k) => String(state[k] ?? ""));
          };
          listeners.add(render);
          render();
          return state;
        }
      };
    }
    const vm = createMiniApp({
      data() { return { message: "Hello Vue 3!" }; }
    }).mount("#hello-vue");
    window.__initial = document.querySelector("#hello-vue").textContent.trim();
    vm.message = "渐进式视图更新";
    window.__updated = document.querySelector("#hello-vue").textContent.trim();
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("({initial: window.__initial, updated: window.__updated, cls: document.querySelector('#hello-vue').className})")
    expected = {"initial": "Hello Vue 3!", "updated": "渐进式视图更新", "cls": "demo"}
    return dict(name="declarative_hello_mount", expected=expected, actual=actual, passed=(actual == expected))


def case_template_directives_if_for(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="app">
    <p id="banner" data-v-if="visible">Vue 3 条件渲染已激活</p>
    <ul id="prereq-list"></ul>
  </div>
  <script>
    const listeners = new Set();
    const state = new Proxy({ visible: false, items: ["HTML", "CSS", "JavaScript"] }, {
      set(t, k, v) { t[k] = v; listeners.forEach((f) => f()); return true; }
    });
    const banner = document.getElementById("banner");
    const placeholder = document.createComment("v-if");
    const parent = banner.parentNode;
    const ul = document.getElementById("prereq-list");
    function render() {
      if (state.visible) {
        if (placeholder.parentNode) parent.replaceChild(banner, placeholder);
      } else {
        if (banner.parentNode) parent.replaceChild(placeholder, banner);
      }
      ul.innerHTML = "";
      for (const item of state.items) {
        const li = document.createElement("li");
        li.textContent = item;
        ul.appendChild(li);
      }
    }
    listeners.add(render);
    render();
    window.__step1 = {
      bannerInDom: !!document.getElementById("banner"),
      items: Array.from(ul.querySelectorAll("li")).map((n) => n.textContent)
    };
    state.visible = true;
    state.items = [...state.items, "Vue 3"];
    window.__step2 = {
      bannerInDom: !!document.getElementById("banner"),
      bannerText: document.getElementById("banner").textContent,
      items: Array.from(ul.querySelectorAll("li")).map((n) => n.textContent)
    };
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("({step1: window.__step1, step2: window.__step2})")
    expected = {
        "step1": {"bannerInDom": False, "items": ["HTML", "CSS", "JavaScript"]},
        "step2": {"bannerInDom": True, "bannerText": "Vue 3 条件渲染已激活", "items": ["HTML", "CSS", "JavaScript", "Vue 3"]},
    }
    return dict(name="template_directives_if_for", expected=expected, actual=actual, passed=(actual == expected))


def case_two_way_v_model_binding(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <input id="course-input" type="text" />
  <span id="course-preview"></span>
  <script>
    const input = document.getElementById("course-input");
    const preview = document.getElementById("course-preview");
    const model = new Proxy({ text: "Vue 3" }, {
      set(t, k, v) {
        t[k] = v;
        if (input.value !== v) input.value = v;
        preview.textContent = v;
        return true;
      }
    });
    input.value = model.text;
    preview.textContent = model.text;
    input.addEventListener("input", (e) => { model.text = e.target.value; });
    window.__model = model;
  </script>
</body></html>"""
    page.set_content(html)
    page.fill("#course-input", "双向数据绑定")
    after_user_input = page.evaluate("({state: window.__model.text, preview: document.getElementById('course-preview').textContent})")
    page.evaluate("window.__model.text = '程序写入同步'")
    after_state_write = page.evaluate("({inputVal: document.getElementById('course-input').value, preview: document.getElementById('course-preview').textContent})")
    actual = {"after_user_input": after_user_input, "after_state_write": after_state_write}
    expected = {
        "after_user_input": {"state": "双向数据绑定", "preview": "双向数据绑定"},
        "after_state_write": {"inputVal": "程序写入同步", "preview": "程序写入同步"},
    }
    return dict(name="two_way_v_model_binding", expected=expected, actual=actual, passed=(actual == expected))


def case_vdom_minimal_patch_and_component(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <ul id="vdom-list"></ul>
  <div id="comp-host"></div>
  <script>
  (() => {
    const ul = document.getElementById("vdom-list");
    let prevVNodes = [];
    function patchList(nextItems) {
      const nextVNodes = nextItems.map((it) => ({ key: it.id, text: it.label, el: null }));
      const prevByKey = new Map(prevVNodes.map((n) => [n.key, n]));
      let domWrites = 0;
      for (const vn of nextVNodes) {
        const old = prevByKey.get(vn.key);
        if (old) {
          vn.el = old.el;
          if (old.text !== vn.text) {
            vn.el.textContent = vn.text;
            domWrites++;
          }
        } else {
          const li = document.createElement("li");
          li.dataset.key = String(vn.key);
          li.textContent = vn.text;
          ul.appendChild(li);
          vn.el = li;
          domWrites++;
        }
      }
      prevVNodes = nextVNodes;
      return domWrites;
    }
    const initWrites = patchList([{ id: 1, label: "响应式" }, { id: 2, label: "组件化" }, { id: 3, label: "虚拟DOM" }]);
    const firstLiBefore = ul.children[0];
    const patchWrites = patchList([{ id: 1, label: "响应式" }, { id: 2, label: "组合式组件" }, { id: 3, label: "虚拟DOM" }]);
    const sameFirstNode = (ul.children[0] === firstLiBefore);

    function mountCounter(host, id, start) {
      let count = start;
      const btn = document.createElement("button");
      btn.id = id;
      const render = () => { btn.textContent = `${id}:${count}`; };
      btn.addEventListener("click", () => { count++; render(); });
      render();
      host.appendChild(btn);
    }
    const host = document.getElementById("comp-host");
    mountCounter(host, "c1", 0);
    mountCounter(host, "c2", 10);
    window.__vdom = { initWrites, patchWrites, sameFirstNode, labels: Array.from(ul.children).map((n) => n.textContent) };
  })();
  </script>
</body></html>"""
    page.set_content(html)
    page.click("#c1")
    page.click("#c1")
    page.click("#c2")
    actual = page.evaluate("({...window.__vdom, c1: document.getElementById('c1').textContent, c2: document.getElementById('c2').textContent})")
    expected = {
        "initWrites": 3,
        "patchWrites": 1,
        "sameFirstNode": True,
        "labels": ["响应式", "组合式组件", "虚拟DOM"],
        "c1": "c1:2",
        "c2": "c2:11",
    }
    return dict(name="vdom_minimal_patch_and_component", expected=expected, actual=actual, passed=(actual == expected))


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            cases = [
                case_declarative_hello_mount(page),
                case_template_directives_if_for(page),
                case_two_way_v_model_binding(page),
                case_vdom_minimal_patch_and_component(page),
            ]
        finally:
            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-tutorial-lab/explore-tutorial.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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