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

离线 Chromium 核对六大核心 Vue 3 指令的 DOM 与计算样式行为

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

SVG_A = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Crect width='24' height='24' fill='%2342b883'/%3E%3C/svg%3E"
SVG_B = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Ccircle cx='12' cy='12' r='10' fill='%2335495e'/%3E%3C/svg%3E"

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>Vue3 Directives Offline Lab</title>
  <style>
    #light-glow {{ width: 40px; height: 40px; background: #ffe066; }}
  </style>
</head>
<body>
  <section id="sec-model-bind">
    <input id="vm-input" type="text" />
    <p id="vm-text"></p>
    <img id="bind-img" alt="icon" />
  </section>

  <section id="sec-if-else">
    <div id="if-wrap"></div>
  </section>

  <section id="sec-for">
    <ul id="for-list"></ul>
  </section>

  <section id="sec-on-show">
    <div id="light-glow"></div>
    <button id="btn-light">开/关</button>
    <button id="btn-show">显示/隐藏</button>
    <p id="show-p">Hello Vue!</p>
  </section>

  <script>
  function reactive(obj, onChange) {{
    return new Proxy(obj, {{
      set(t, k, v) {{ t[k] = v; onChange(); return true; }}
    }});
  }}

  // 1. v-model & v-bind:src
  const mbState = reactive({{
    message: 'Hello Vue!!',
    imageSrc: "{SVG_A}"
  }}, renderMB);
  function renderMB() {{
    const inp = document.getElementById('vm-input');
    if (inp.value !== mbState.message) inp.value = mbState.message;
    document.getElementById('vm-text').textContent = mbState.message;
    document.getElementById('bind-img').setAttribute('src', mbState.imageSrc);
  }}
  document.getElementById('vm-input').addEventListener('input', e => {{
    mbState.message = e.target.value;
  }});
  renderMB();
  window.__mbState = mbState;
  window.__svgB = "{SVG_B}";

  // 2. v-if / v-else
  const ifState = reactive({{ showMessage: true }}, renderIf);
  function renderIf() {{
    const wrap = document.getElementById('if-wrap');
    wrap.innerHTML = ifState.showMessage
      ? '<p id="msg-true">Hello Vue!</p>'
      : '<p id="msg-false">Goodbye Vue!</p>';
  }}
  renderIf();
  window.__ifState = ifState;

  // 3. v-for
  const forItems = [
    {{ id: 1, text: 'Item 1' }},
    {{ id: 2, text: 'Item 2' }},
    {{ id: 3, text: 'Item 3' }}
  ];
  function renderFor() {{
    const ul = document.getElementById('for-list');
    ul.innerHTML = '';
    for (const item of forItems) {{
      const li = document.createElement('li');
      li.dataset.key = String(item.id);
      li.textContent = item.text;
      ul.appendChild(li);
    }}
  }}
  renderFor();
  window.__pushForItem = (item) => {{ forItems.push(item); renderFor(); }};

  // 4. v-on + v-show
  const showState = reactive({{ lightOn: false, showMessage: true }}, renderShow);
  function renderShow() {{
    document.getElementById('light-glow').style.display = showState.lightOn ? '' : 'none';
    document.getElementById('show-p').style.display = showState.showMessage ? '' : 'none';
  }}
  document.getElementById('btn-light').addEventListener('click', () => {{
    showState.lightOn = !showState.lightOn;
  }});
  document.getElementById('btn-show').addEventListener('click', () => {{
    showState.showMessage = !showState.showMessage;
  }});
  renderShow();
  </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(viewport={"width": 900, "height": 600})
        page.set_content(HTML_DOC)

        # Case 1: v-model two-way sync & v-bind:src
        init_text = page.locator("#vm-text").inner_text()
        page.fill("#vm-input", "Vue3 Directives")
        c1 = page.evaluate("""() => {
            const img = document.getElementById('bind-img');
            const srcBefore = img.getAttribute('src').includes('rect');
            window.__mbState.imageSrc = window.__svgB;
            const srcAfter = img.getAttribute('src').includes('circle');
            return {
                after_text: document.getElementById('vm-text').textContent,
                src_before_rect: srcBefore,
                src_after_circle: srcAfter
            };
        }""")
        c1["init_text"] = init_text
        exp1 = {
            "init_text": "Hello Vue!!",
            "after_text": "Vue3 Directives",
            "src_before_rect": True,
            "src_after_circle": True,
        }
        cases.append({"name": "vmodel_and_vbind_attr", "passed": c1 == exp1, "expected": exp1, "actual": c1})

        # Case 2: v-if / v-else DOM creation & destruction
        c2 = page.evaluate("""() => {
            const t1 = {
                true_el: document.getElementById('msg-true')?.textContent || null,
                false_el: document.getElementById('msg-false')?.textContent || null
            };
            window.__ifState.showMessage = false;
            const t2 = {
                true_el: document.getElementById('msg-true')?.textContent || null,
                false_el: document.getElementById('msg-false')?.textContent || null
            };
            return { when_true: t1, when_false: t2 };
        }""")
        exp2 = {
            "when_true": {"true_el": "Hello Vue!", "false_el": None},
            "when_false": {"true_el": None, "false_el": "Goodbye Vue!"},
        }
        cases.append({"name": "vif_velse_conditional_dom", "passed": c2 == exp2, "expected": exp2, "actual": c2})

        # Case 3: v-for keyed list rendering
        c3 = page.evaluate("""() => {
            const init = Array.from(document.querySelectorAll('#for-list li')).map(li => li.dataset.key + ':' + li.textContent);
            window.__pushForItem({ id: 4, text: 'Item 4' });
            const after = Array.from(document.querySelectorAll('#for-list li')).map(li => li.dataset.key + ':' + li.textContent);
            return { init, after };
        }""")
        exp3 = {
            "init": ["1:Item 1", "2:Item 2", "3:Item 3"],
            "after": ["1:Item 1", "2:Item 2", "3:Item 3", "4:Item 4"],
        }
        cases.append({"name": "vfor_keyed_list", "passed": c3 == exp3, "expected": exp3, "actual": c3})

        # Case 4: v-on click handler + v-show CSS display toggle
        before_show = page.evaluate("""() => ({
            light_display: getComputedStyle(document.getElementById('light-glow')).display,
            msg_display: getComputedStyle(document.getElementById('show-p')).display,
            both_in_dom: Boolean(document.getElementById('light-glow') && document.getElementById('show-p'))
        })""")
        page.click("#btn-light")
        page.click("#btn-show")
        after_show = page.evaluate("""() => ({
            light_display: getComputedStyle(document.getElementById('light-glow')).display,
            msg_display: getComputedStyle(document.getElementById('show-p')).display,
            both_in_dom: Boolean(document.getElementById('light-glow') && document.getElementById('show-p'))
        })""")
        c4 = {"before": before_show, "after": after_show}
        exp4 = {
            "before": {"light_display": "none", "msg_display": "block", "both_in_dom": True},
            "after": {"light_display": "block", "msg_display": "none", "both_in_dom": True},
        }
        cases.append({"name": "von_and_vshow_display_toggle", "passed": c4 == exp4, "expected": exp4, "actual": c4})

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

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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