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

离线 Chromium 验证表单双向绑定与 v-model 修饰符

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-vue-forms.py
explore-vue-forms.py218 行
"""Offline Chromium runtime verification for Vue 2 Chapter 12: vue-forms."""
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: input and textarea two-way binding
        page.set_content("""
        <!doctype html>
        <html><body>
          <input id="txt-in" value="Vue2">
          <p id="txt-out">消息是: Vue2</p>
          <textarea id="ta-in">第一行\n第二行</textarea>
          <p id="ta-out" style="white-space: pre">第一行\n第二行</p>
          <script>
            window.__form1 = { message: 'Vue2', message2: '第一行\\n第二行' };
            const txtIn = document.getElementById('txt-in');
            const txtOut = document.getElementById('txt-out');
            txtIn.addEventListener('input', (e) => {
              window.__form1.message = e.target.value;
              txtOut.textContent = '消息是: ' + window.__form1.message;
            });
            const taIn = document.getElementById('ta-in');
            const taOut = document.getElementById('ta-out');
            taIn.addEventListener('input', (e) => {
              window.__form1.message2 = e.target.value;
              taOut.textContent = window.__form1.message2;
            });
          </script>
        </body></html>
        """)
        page.fill("#txt-in", "双向绑定")
        page.fill("#ta-in", "蓝色天空\nhttps://example.org")
        actual1 = {
            "message": page.evaluate("window.__form1.message"),
            "txtOut": page.locator("#txt-out").inner_text(),
            "message2": page.evaluate("window.__form1.message2"),
            "whiteSpace": page.evaluate("getComputedStyle(document.getElementById('ta-out')).whiteSpace"),
        }
        expected1 = {
            "message": "双向绑定",
            "txtOut": "消息是: 双向绑定",
            "message2": "蓝色天空\nhttps://example.org",
            "whiteSpace": "pre",
        }
        cases.append(make_case("input_and_textarea_two_way", expected1, actual1))

        # Case 2: single boolean checkbox and multi-checkbox array binding
        page.set_content("""
        <!doctype html>
        <html><body>
          <input type="checkbox" id="single-cb">
          <label id="single-lbl" for="single-cb">false</label>
          <input type="checkbox" id="cb-a" value="Alpha" class="multi-cb">
          <input type="checkbox" id="cb-b" value="Beta" class="multi-cb">
          <input type="checkbox" id="cb-c" value="Gamma" class="multi-cb">
          <span id="multi-out">[]</span>
          <script>
            window.__cb = { checked: false, checkedNames: [] };
            document.getElementById('single-cb').addEventListener('change', (e) => {
              window.__cb.checked = e.target.checked;
              document.getElementById('single-lbl').textContent = String(window.__cb.checked);
            });
            document.querySelectorAll('.multi-cb').forEach(el => {
              el.addEventListener('change', () => {
                window.__cb.checkedNames = Array.from(document.querySelectorAll('.multi-cb:checked')).map(x => x.value);
                document.getElementById('multi-out').textContent = JSON.stringify(window.__cb.checkedNames);
              });
            });
          </script>
        </body></html>
        """)
        page.check("#single-cb")
        page.check("#cb-a")
        page.check("#cb-b")
        page.check("#cb-c")
        page.uncheck("#cb-b")
        actual2 = {
            "checked": page.evaluate("window.__cb.checked"),
            "singleLabel": page.locator("#single-lbl").inner_text(),
            "checkedNames": page.evaluate("window.__cb.checkedNames"),
        }
        expected2 = {
            "checked": True,
            "singleLabel": "true",
            "checkedNames": ["Alpha", "Gamma"],
        }
        cases.append(make_case("checkbox_single_and_multi", expected2, actual2))

        # Case 3: radio buttons and select dropdown binding
        page.set_content("""
        <!doctype html>
        <html><body>
          <input type="radio" name="site" id="r-vue" value="Vue" checked>
          <input type="radio" name="site" id="r-mdn" value="MDN">
          <span id="radio-out">选中值为: Vue</span>
          <select id="site-select">
            <option value="">选择一个网站</option>
            <option value="vuejs.org">Vue</option>
            <option value="developer.mozilla.org">MDN</option>
          </select>
          <div id="select-out">选择的网站是: </div>
          <script>
            window.__rs = { picked: 'Vue', selected: '' };
            document.querySelectorAll('input[name="site"]').forEach(r => {
              r.addEventListener('change', (e) => {
                window.__rs.picked = e.target.value;
                document.getElementById('radio-out').textContent = '选中值为: ' + window.__rs.picked;
              });
            });
            document.getElementById('site-select').addEventListener('change', (e) => {
              window.__rs.selected = e.target.value;
              document.getElementById('select-out').textContent = '选择的网站是: ' + window.__rs.selected;
            });
          </script>
        </body></html>
        """)
        initial_picked = page.evaluate("window.__rs.picked")
        page.check("#r-mdn")
        page.select_option("#site-select", "vuejs.org")
        actual3 = {
            "initialPicked": initial_picked,
            "pickedAfterClick": page.evaluate("window.__rs.picked"),
            "radioOut": page.locator("#radio-out").inner_text(),
            "selected": page.evaluate("window.__rs.selected"),
            "selectOut": page.locator("#select-out").inner_text(),
        }
        expected3 = {
            "initialPicked": "Vue",
            "pickedAfterClick": "MDN",
            "radioOut": "选中值为: MDN",
            "selected": "vuejs.org",
            "selectOut": "选择的网站是: vuejs.org",
        }
        cases.append(make_case("radio_and_select_binding", expected3, actual3))

        # Case 4: v-model modifiers (.lazy, .number, .trim)
        page.set_content("""
        <!doctype html>
        <html><body>
          <input id="in-lazy" />
          <input id="in-num" type="number" />
          <input id="in-num-text" type="text" />
          <input id="in-trim" />
          <script>
            window.__mods = { lazy: '', lazyOnInput: '', rawNumType: '', numVal: null, numType: '', fallbackVal: null, trimmed: '' };
            document.getElementById('in-lazy').addEventListener('change', (e) => {
              window.__mods.lazy = e.target.value;
            });
            document.getElementById('in-num').addEventListener('input', (e) => {
              window.__mods.rawNumType = typeof e.target.value;
              const n = parseFloat(e.target.value);
              window.__mods.numVal = isNaN(n) ? e.target.value : n;
              window.__mods.numType = typeof window.__mods.numVal;
            });
            document.getElementById('in-num-text').addEventListener('input', (e) => {
              const n = parseFloat(e.target.value);
              window.__mods.fallbackVal = isNaN(n) ? e.target.value : n;
            });
            document.getElementById('in-trim').addEventListener('input', (e) => {
              window.__mods.trimmed = e.target.value.trim();
            });
          </script>
        </body></html>
        """)
        # Type into lazy without blur/change first
        page.locator("#in-lazy").type("pending")
        lazy_before_blur = page.evaluate("window.__mods.lazy")
        page.locator("#in-lazy").dispatch_event("change")
        lazy_after_change = page.evaluate("window.__mods.lazy")

        page.fill("#in-num", "42")
        page.fill("#in-num-text", "abc")
        page.fill("#in-trim", "  vue 2 form  ")
        actual4 = {
            "lazyBeforeChange": lazy_before_blur,
            "lazyAfterChange": lazy_after_change,
            "rawHtmlNumberType": page.evaluate("window.__mods.rawNumType"),
            "numberValue": page.evaluate("window.__mods.numVal"),
            "numberType": page.evaluate("window.__mods.numType"),
            "nanFallback": page.evaluate("window.__mods.fallbackVal"),
            "trimmed": page.evaluate("window.__mods.trimmed"),
        }
        expected4 = {
            "lazyBeforeChange": "",
            "lazyAfterChange": "pending",
            "rawHtmlNumberType": "string",
            "numberValue": 42,
            "numberType": "number",
            "nanFallback": "abc",
            "trimmed": "vue 2 form",
        }
        cases.append(make_case("v_model_modifiers_lazy_number_trim", 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-forms-lab/explore-vue-forms.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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