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

离线 Chromium 验证自定义事件、data 隔离与组件 v-model

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-vue-component-custom-event.py
explore-vue-component-custom-event.py195 行
"""Offline Chromium runtime verification for Vue 2 Chapter 14: vue-component-custom-event."""
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()

        # Case 1: $on / $emit child-to-parent custom event + .native root event
        page.set_content("""
        <!doctype html>
        <html><body>
          <p id="total">0</p>
          <div id="counters"></div>
          <div id="native-comp"><button id="native-root">Native Root</button></div>
          <script>
            class EventBus {
              constructor() { this.map = {}; }
              $on(evt, fn) { (this.map[evt] = this.map[evt] || []).push(fn); }
              $emit(evt, ...args) { (this.map[evt] || []).forEach(fn => fn(...args)); }
            }
            window.__parent = { total: 0, nativeHits: 0 };
            function createButtonCounter(id) {
              const bus = new EventBus();
              const state = { counter: 0 };
              const btn = document.createElement('button');
              btn.id = id;
              btn.textContent = '0';
              btn.addEventListener('click', () => {
                state.counter += 1;
                btn.textContent = String(state.counter);
                bus.$emit('increment');
              });
              bus.$on('increment', () => {
                window.__parent.total += 1;
                document.getElementById('total').textContent = String(window.__parent.total);
              });
              document.getElementById('counters').appendChild(btn);
            }
            createButtonCounter('bc1');
            createButtonCounter('bc2');
            // .native binds directly to root element
            document.getElementById('native-root').addEventListener('click', () => {
              window.__parent.nativeHits += 1;
            });
          </script>
        </body></html>
        """)
        page.click("#bc1")
        page.click("#bc1")
        page.click("#bc2")
        page.click("#native-root")
        actual1 = {
            "bc1": int(page.locator("#bc1").inner_text()),
            "bc2": int(page.locator("#bc2").inner_text()),
            "total": int(page.locator("#total").inner_text()),
            "nativeHits": page.evaluate("window.__parent.nativeHits"),
        }
        expected1 = {"bc1": 2, "bc2": 1, "total": 3, "nativeHits": 1}
        cases.append(make_case("child_emit_and_parent_on", expected1, actual1))

        # Case 2: data must be a function (isolated copies vs shared object pollution)
        page.set_content("""
        <!doctype html>
        <html><body>
          <div id="isolated"></div>
          <div id="shared"></div>
          <script>
            function mountCounters(containerId, dataFactory) {
              const host = document.getElementById(containerId);
              const instances = [];
              for (let i = 0; i < 3; i++) {
                const state = dataFactory();
                const btn = document.createElement('button');
                btn.id = containerId + '-' + i;
                const render = () => { btn.textContent = String(state.count); };
                render();
                instances.push({ state, render });
                btn.addEventListener('click', () => {
                  state.count += 1;
                  instances.forEach(inst => inst.render());
                });
                host.appendChild(btn);
              }
            }
            mountCounters('isolated', () => ({ count: 0 }));
            const sharedObj = { count: 0 };
            mountCounters('shared', () => sharedObj);
          </script>
        </body></html>
        """)
        page.click("#isolated-0")
        page.click("#shared-0")
        actual2 = {
            "isolated": [int(x) for x in page.locator("#isolated button").all_inner_texts()],
            "shared": [int(x) for x in page.locator("#shared button").all_inner_texts()],
        }
        expected2 = {"isolated": [1, 0, 0], "shared": [1, 1, 1]}
        cases.append(make_case("data_function_vs_shared_object", expected2, actual2))

        # Case 3: custom component default v-model (value prop + input event)
        page.set_content("""
        <!doctype html>
        <html><body>
          <p><input id="custom-num" value="100"></p>
          <p id="parent-num">输入的数字为:100</p>
          <script>
            window.__numModel = 100;
            document.getElementById('custom-num').addEventListener('input', (e) => {
              // Equivalent to $emit('input', $event.target.value)
              window.__numModel = e.target.value;
              document.getElementById('parent-num').textContent = '输入的数字为:' + window.__numModel;
            });
          </script>
        </body></html>
        """)
        initial_num = page.locator("#parent-num").inner_text()
        page.fill("#custom-num", "256")
        actual3 = {
            "initial": initial_num,
            "updated": page.locator("#parent-num").inner_text(),
            "modelValue": page.evaluate("window.__numModel"),
        }
        expected3 = {
            "initial": "输入的数字为:100",
            "updated": "输入的数字为:256",
            "modelValue": "256",
        }
        cases.append(make_case("custom_component_v_model_default", expected3, actual3))

        # Case 4: custom component model option ({ prop: 'checked', event: 'change' })
        page.set_content("""
        <!doctype html>
        <html><body>
          <input type="checkbox" id="base-cb" checked>
          <div id="love-box">如果选择框打勾我就会显示。</div>
          <script>
            window.__lovingVue = true;
            const cb = document.getElementById('base-cb');
            const box = document.getElementById('love-box');
            function sync() {
              cb.checked = window.__lovingVue;
              box.style.display = window.__lovingVue ? 'block' : 'none';
            }
            sync();
            cb.addEventListener('change', (e) => {
              // Equivalent to $emit('change', $event.target.checked)
              window.__lovingVue = e.target.checked;
              sync();
            });
          </script>
        </body></html>
        """)
        init_disp = page.evaluate("getComputedStyle(document.getElementById('love-box')).display")
        page.uncheck("#base-cb")
        after_uncheck_disp = page.evaluate("getComputedStyle(document.getElementById('love-box')).display")
        after_uncheck_val = page.evaluate("window.__lovingVue")
        page.check("#base-cb")
        after_recheck_disp = page.evaluate("getComputedStyle(document.getElementById('love-box')).display")
        actual4 = {
            "initialDisplay": init_disp,
            "afterUncheckDisplay": after_uncheck_disp,
            "afterUncheckModel": after_uncheck_val,
            "afterRecheckDisplay": after_recheck_disp,
        }
        expected4 = {
            "initialDisplay": "block",
            "afterUncheckDisplay": "none",
            "afterUncheckModel": False,
            "afterRecheckDisplay": "block",
        }
        cases.append(make_case("custom_component_model_option", expected4, actual4))

        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-component-custom-event-lab/explore-vue-component-custom-event.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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