蓝色天空网mbsky.com · 知识 · 实践 · 创造Vue3 · 本地阅读预览
教程 / 前端开发 / Vue3

Vue3 条件语句

核对 Vue 3 条件渲染指令 v-if、template 分组条件、v-else、v-else-if 多分支链及 v-show 与 v-if 的 DOM/CSS 实测差异。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

条件渲染指令总览与 v-if 单元素 / template 分组

Vue 3 模板提供 `v-if`、`v-else-if`、`v-else` 与 `v-show` 四类条件控制指令:`v-if` 在条件为 `false` 时不会把元素渲染进 DOM,适合条件变动不频繁的场景;`v-show` 始终把元素保留在 DOM 中仅切换显示样式,适合高频切换;`v-else-if` 与 `v-else` 则配合 `v-if` 构建多分支逻辑。

`v-if` 按表达式真假决定是否插入对应节点。因为指令必须写在单个元素上,当需要同步控制多个兄弟元素时,可用内置包装标签 `<template v-if="seen">` 包裹整组内容,最终渲染出的 DOM 不会残留 `<template>` 节点本身。本站离线 Chromium 实测验证 `seen: true` 时单元素渲染 `现在你看到我了`,`<template>` 分组直接挂载 `['H1:网站', 'P:Alpha', 'P:Beta', 'P:Gamma']` 四个子节点且 DOM 中不含 `<template>` 标签;将 `seen` 设为 `false` 后所有受控节点彻底从 DOM 移除(子元素数为 `0`)。

v-else 与 v-else-if 多分支条件链

`v-else` 紧跟在 `v-if`(或 `v-else-if`)之后,用于在前面所有条件均为假时渲染兜底块(例如按数值是否大于 `0.5` 分流显示两段提示)。本站离线 Chromium 实测验证阈值条件 `score = 0.72` 时仅挂载 `数值大于 0.5` 节点,切换为 `score = 0.25` 时仅挂载 `数值小于等于 0.5` 节点,两个分支互斥存在。

在 `v-if` 与 `v-else` 之间可串联任意数量的 `v-else-if` 实现多分支匹配(例如判断 `type` 为 `'A'`、`'B'`、`'C'` 或其他值)。需注意 `v-else-if` 与 `v-else` 必须紧邻前一个 `v-if` 或 `v-else-if` 兄弟元素,中间不能插入无关节点。本站离线 Chromium 实测依次将 `type` 切换为 `'A'`、`'B'`、`'C'`、`'D'`,每次 DOM 中都仅存在 1 个分支节点,文本精确对应 `A`、`B`、`C`、`Not A/B/C`。

v-show 与 v-if 的实测对比与选型

`v-show` 同样依据表达式真假控制元素是否可见,但它不会从 DOM 中销毁元素,而是切换 CSS `display` 属性;当条件需要高频来回切换时,`v-show` 避免了反复创建销毁 DOM 与子组件的开销。本站离线 Chromium 实测对比同步绑定的 `<h1 v-show="ok">` 与 `<h1 v-if="ok">`:当 `ok` 按 `true -> false -> true` 翻转时,`v-show` 元素始终存在于 DOM 中,计算样式 `display` 依次为 `block -> none -> block`;而 `v-if` 元素在 `false` 时从 DOM 完全移除,恢复 `true` 时重新创建。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对 template v-if 不残留包装标签、score 0.72/0.25 互斥分支、type A/B/C/D 唯一分支匹配,以及 v-show 保留 DOM 切换 display block/none/block 而 v-if 销毁重建。
离线 Chromium 核对 v-if/template 分组、v-else-if 多分支与 v-show 样式切换

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:3df777a87730bfd5c477f1d286a15261a32d4d6490db7a029b85f0ccf2455898

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Vue3 条件语句实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:12346ee9153fe3699e0e107785e919c17b2d48f422bd3503e5727faebca69360

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在多元素条件渲染时应将 v-if 写在 <template> 上,且 v-show 能否同样写在 <template> 上?

展开参考解答

<template> 作为不可见包装器在渲染时会被展开,不会引入多余的 <div> 破坏表格或弹性布局;但 v-show 依赖给真实元素设置 display: none,因此不能用于 <template> 元素,也不配合 v-else 使用。

规范与官方依据