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

离线 Chromium 核对 v-if/template 分组、v-else-if 多分支与 v-show 样式切换

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

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 v-if Offline Lab</title></head>
<body>
  <div id="app-single"></div>
  <div id="app-tpl"></div>
  <div id="app-else"></div>
  <div id="app-elseif"></div>
  <div id="app-show">
    <h1 id="show-h1">Hello!</h1>
    <div id="if-cmp-wrap"></div>
  </div>

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

  // 1. v-if single element + <template v-if> group (renders children directly without <template> wrapper)
  const s1 = reactive({ seen: true }, renderS1);
  function renderS1() {
    document.getElementById('app-single').innerHTML = s1.seen
      ? '<p id="single-p">现在你看到我了</p>'
      : '';
    const tplHost = document.getElementById('app-tpl');
    tplHost.innerHTML = '';
    if (s1.seen) {
      const frag = document.createDocumentFragment();
      const h1 = document.createElement('h1'); h1.textContent = '网站'; frag.appendChild(h1);
      for (const name of ['Alpha', 'Beta', 'Gamma']) {
        const p = document.createElement('p'); p.textContent = name; frag.appendChild(p);
      }
      tplHost.appendChild(frag);
    }
  }
  renderS1();
  window.__s1 = s1;

  // 2. v-if / v-else branching
  const s2 = reactive({ score: 0.72 }, renderS2);
  function renderS2() {
    const host = document.getElementById('app-else');
    host.innerHTML = s2.score > 0.5
      ? '<div id="branch-hi">数值大于 0.5</div>'
      : '<div id="branch-lo">数值小于等于 0.5</div>';
  }
  renderS2();
  window.__s2 = s2;

  // 3. v-if / v-else-if / v-else chain
  const s3 = reactive({ type: 'C' }, renderS3);
  function renderS3() {
    const host = document.getElementById('app-elseif');
    let label = 'Not A/B/C';
    if (s3.type === 'A') label = 'A';
    else if (s3.type === 'B') label = 'B';
    else if (s3.type === 'C') label = 'C';
    host.innerHTML = `<div class="type-branch">${label}</div>`;
  }
  renderS3();
  window.__s3 = s3;

  // 4. v-show vs v-if
  const s4 = reactive({ ok: true }, renderS4);
  function renderS4() {
    document.getElementById('show-h1').style.display = s4.ok ? '' : 'none';
    document.getElementById('if-cmp-wrap').innerHTML = s4.ok ? '<h1 id="if-h1">Hello!</h1>' : '';
  }
  renderS4();
  window.__s4 = s4;
  </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-if on single element & <template v-if> group
        c1 = page.evaluate("""() => {
            const tplHost = document.getElementById('app-tpl');
            const onTrue = {
                single_text: document.getElementById('single-p')?.textContent || null,
                tpl_children: Array.from(tplHost.children).map(el => el.tagName + ':' + el.textContent),
                has_template_tag: tplHost.querySelector('template') !== null
            };
            window.__s1.seen = false;
            const onFalse = {
                single_exists: document.getElementById('single-p') !== null,
                tpl_child_count: tplHost.childElementCount
            };
            return { on_true: onTrue, on_false: onFalse };
        }""")
        exp1 = {
            "on_true": {
                "single_text": "现在你看到我了",
                "tpl_children": ["H1:网站", "P:Alpha", "P:Beta", "P:Gamma"],
                "has_template_tag": False,
            },
            "on_false": {"single_exists": False, "tpl_child_count": 0},
        }
        cases.append({"name": "vif_single_and_template_group", "passed": c1 == exp1, "expected": exp1, "actual": c1})

        # Case 2: v-if / v-else branching
        c2 = page.evaluate("""() => {
            const hi = {
                hi_text: document.getElementById('branch-hi')?.textContent || null,
                lo_exists: document.getElementById('branch-lo') !== null
            };
            window.__s2.score = 0.25;
            const lo = {
                hi_exists: document.getElementById('branch-hi') !== null,
                lo_text: document.getElementById('branch-lo')?.textContent || null
            };
            return { gt_half: hi, le_half: lo };
        }""")
        exp2 = {
            "gt_half": {"hi_text": "数值大于 0.5", "lo_exists": False},
            "le_half": {"hi_exists": False, "lo_text": "数值小于等于 0.5"},
        }
        cases.append({"name": "vif_velse_branching", "passed": c2 == exp2, "expected": exp2, "actual": c2})

        # Case 3: v-else-if multi-branch chain
        c3 = page.evaluate("""() => {
            const out = {};
            for (const val of ['A', 'B', 'C', 'D']) {
                window.__s3.type = val;
                const nodes = document.querySelectorAll('#app-elseif .type-branch');
                out[val] = { count: nodes.length, text: nodes[0]?.textContent || null };
            }
            return out;
        }""")
        exp3 = {
            "A": {"count": 1, "text": "A"},
            "B": {"count": 1, "text": "B"},
            "C": {"count": 1, "text": "C"},
            "D": {"count": 1, "text": "Not A/B/C"},
        }
        cases.append({"name": "velse_if_multi_branch", "passed": c3 == exp3, "expected": exp3, "actual": c3})

        # Case 4: v-show (CSS display) vs v-if (DOM removal)
        c4 = page.evaluate("""() => {
            const snap = () => ({
                show_in_dom: document.getElementById('show-h1') !== null,
                show_display: getComputedStyle(document.getElementById('show-h1')).display,
                if_in_dom: document.getElementById('if-h1') !== null
            });
            const t1 = snap();
            window.__s4.ok = false;
            const t2 = snap();
            window.__s4.ok = true;
            const t3 = snap();
            return { init_true: t1, toggled_false: t2, restored_true: t3 };
        }""")
        exp4 = {
            "init_true": {"show_in_dom": True, "show_display": "block", "if_in_dom": True},
            "toggled_false": {"show_in_dom": True, "show_display": "none", "if_in_dom": False},
            "restored_true": {"show_in_dom": True, "show_display": "block", "if_in_dom": True},
        }
        cases.append({"name": "vshow_vs_vif_dom_and_css", "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-v-if-lab/explore-v-if.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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