Vue.js 条件语句
核对 Vue 2 条件渲染指令 v-if、template 分组条件块、v-else、v-else-if 多分支链,以及 v-show 与 v-if 在 DOM 与 CSS 层面的核心差异。
学完这一章,你能够
- 核对 Vue 2 条件渲染指令 v-if、template 分组条件块、v-else、v-else-if 多分支链,以及 v-show 与 v-if 在 DOM 与 CSS 层面的核心差异。
v-if 单元素与 template 分组条件渲染
Vue 中通过 `v-if` 指令按表达式真假决定是否渲染目标节点:当条件为真时插入元素,为假时从 DOM 中彻底移除。相比 Handlebars 等字符串模板需要使用 `{{#if ok}} ... {{/if}}` 包裹条件区块,Vue 直接将 `v-if` 声明在元素上;若希望一次切换多个同级元素而又不想额外引入冗余的包裹标签,可将 `v-if` 写在 `<template>` 上,最终渲染结果不包含 `<template>` 本身。本站离线 Chromium 实测初始 `seen=true, ok=true` 时 `#seen-p` 存在、`<template v-if="ok">` 展开为 3 个子节点且 DOM 中 `<template>` 标签数为 `0`;将两者改为 `false` 后所有条件节点均被移除(计数归 `0`)。
v-else 与 v-else-if 多分支条件链
借助 `v-else` 可为 `v-if` 提供“否则”分支,典型如根据数值与阈值 `0.5` 的比较结果输出不同提示。本站离线实测以确定性数值驱动分支:`score = 0.72` 时仅渲染 1 个分支节点并显示 `Sorry`,改为 `0.31` 时原节点移除并切换为仅 1 个 `Not sorry` 节点。
从 Vue 2.1.0 起新增的 `v-else-if` 支持链式编写多条件判断(例如依次匹配 `type` 为 `'A'`、`'B'`、`'C'` 及兜底 `Not A/B/C`)。语法上 `v-else` 与 `v-else-if` 必须紧跟在带 `v-if` 或 `v-else-if` 的兄弟元素之后,否则无法识别。本站实测依次将 `vm.type` 设为 `'A'`、`'B'`、`'C'`、`'D'`,DOM 中始终仅挂载唯一匹配分支,输出依次为 `A`、`B`、`C`、`Not A/B/C`。
v-show 与 v-if 的实现机制对比
另一条件展示指令 `v-show`(如 `<h1 v-show="ok">Hello!</h1>`)同样依据表达式真假控制元素可见性,但底层机制截然不同:`v-show` 始终保留元素在 DOM 树中,仅通过切换内联 CSS `display` 属性实现显隐(且不支持 `<template>` 与 `v-else`)。本站离线 Chromium 同屏对比实测:`showFlag` 由 `true` 切为 `false` 后,`v-show` 绑定的 `#show-h1` 仍留在 DOM 中而计算样式 `display` 由 `block` 变为 `none`,同期 `v-if` 绑定的 `#if-h1` 则从 DOM 中完全消失。
离线 Chromium 核验 v-if/<template>、v-else、v-else-if 多分支及 v-show 样式切换
展开查看收起
"""Offline Playwright Chromium lab for Vue 2 Chapter 06 (vue-if)."""
import json
from playwright.sync_api import sync_playwright
MINI_VUE2_IF_JS = r"""
(function (global) {
class Dep {
constructor() { this.subs = new Set(); }
depend() { if (Dep.target) this.subs.add(Dep.target); }
notify() { this.subs.forEach(w => w.update()); }
}
Dep.target = null;
class Watcher {
constructor(vm, getter, cb) {
this.vm = vm;
this.getter = getter;
this.cb = cb;
this.value = this.get();
}
get() {
Dep.target = this;
const v = this.getter.call(this.vm);
Dep.target = null;
return v;
}
update() {
const oldVal = this.value;
const newVal = this.get();
this.value = newVal;
if (this.cb) this.cb.call(this.vm, newVal, oldVal);
}
}
function observe(data) {
Object.keys(data).forEach(key => {
let val = data[key];
const dep = new Dep();
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get() { dep.depend(); return val; },
set(newVal) {
if (newVal === val) return;
val = newVal;
dep.notify();
}
});
});
}
function evalExpr(vm, expr) {
return new Function('with(this){ return (' + expr + '); }').call(vm);
}
function extractNodes(el) {
if (el.tagName === 'TEMPLATE') {
return Array.from(el.content.childNodes).map(n => n.cloneNode(true));
}
return [el];
}
class Vue {
constructor(options) {
this.$data = options.data || {};
observe(this.$data);
Object.keys(this.$data).forEach(k => {
Object.defineProperty(this, k, {
enumerable: true,
configurable: true,
get: () => this.$data[k],
set: (v) => { this.$data[k] = v; }
});
});
this.$el = document.querySelector(options.el);
if (this.$el) this._compile(this.$el);
}
_compile(container) {
const children = Array.from(container.children);
let i = 0;
while (i < children.length) {
const el = children[i];
if (el.hasAttribute('v-if')) {
const chain = [{ kind: 'if', exp: el.getAttribute('v-if'), el }];
el.removeAttribute('v-if');
let j = i + 1;
while (j < children.length) {
const nxt = children[j];
if (nxt.hasAttribute('v-else-if')) {
chain.push({ kind: 'else-if', exp: nxt.getAttribute('v-else-if'), el: nxt });
nxt.removeAttribute('v-else-if');
j++;
} else if (nxt.hasAttribute('v-else')) {
chain.push({ kind: 'else', exp: null, el: nxt });
nxt.removeAttribute('v-else');
j++;
break;
} else {
break;
}
}
const anchor = document.createComment('v-if-chain');
container.insertBefore(anchor, el);
chain.forEach(item => {
item.nodes = extractNodes(item.el);
if (item.el.parentNode) item.el.parentNode.removeChild(item.el);
});
let activeNodes = [];
const updateChain = () => {
activeNodes.forEach(n => { if (n.parentNode) n.parentNode.removeChild(n); });
activeNodes = [];
for (const item of chain) {
const matched = item.kind === 'else' ? true : Boolean(evalExpr(this, item.exp));
if (matched) {
const frag = document.createDocumentFragment();
item.nodes.forEach(n => { frag.appendChild(n); activeNodes.push(n); });
container.insertBefore(frag, anchor.nextSibling);
break;
}
}
};
new Watcher(this, () => {
const results = [];
for (const item of chain) {
if (item.exp !== null) results.push(Boolean(evalExpr(this, item.exp)));
}
return results.join('|');
}, updateChain);
updateChain();
i = j;
} else if (el.hasAttribute('v-show')) {
const exp = el.getAttribute('v-show');
el.removeAttribute('v-show');
const origDisplay = el.style.display === 'none' ? '' : el.style.display;
const apply = (cond) => { el.style.display = cond ? origDisplay : 'none'; };
const w = new Watcher(this, () => Boolean(evalExpr(this, exp)), apply);
apply(w.value);
i++;
} else {
this._compile(el);
i++;
}
}
}
}
global.Vue = Vue;
})(window);
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue 2 条件语句实验</title></head>
<body>
<div id="app">
<section id="sec-basic">
<p id="seen-p" v-if="seen">现在你看到我了</p>
<template v-if="ok">
<h1 class="tpl-child">蓝色天空网</h1>
<p class="tpl-child">条件区块第一段</p>
<p class="tpl-child">条件区块第二段</p>
</template>
</section>
<section id="sec-else">
<div class="branch-else" v-if="score > 0.5">Sorry</div>
<div class="branch-else" v-else>Not sorry</div>
</section>
<section id="sec-elseif">
<div class="branch-type" v-if="type === 'A'">A</div>
<div class="branch-type" v-else-if="type === 'B'">B</div>
<div class="branch-type" v-else-if="type === 'C'">C</div>
<div class="branch-type" v-else>Not A/B/C</div>
</section>
<section id="sec-show">
<h1 id="show-h1" v-show="showFlag">Hello!</h1>
<h1 id="if-h1" v-if="showFlag">Hello!</h1>
</section>
</div>
<script>{MINI_VUE2_IF_JS}</script>
<script>
window.vm = new Vue({{
el: '#app',
data: {{
seen: true,
ok: true,
score: 0.72,
type: 'C',
showFlag: true
}}
}});
</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()
page.set_content(HTML_DOC)
# Case 1: v-if on single element and <template> multi-element group
res1 = page.evaluate("""() => {
const seenInit = document.getElementById('seen-p') !== null;
const tplInitCount = document.querySelectorAll('#sec-basic .tpl-child').length;
const tplTagInDom = document.querySelectorAll('#sec-basic template').length;
window.vm.seen = false;
window.vm.ok = false;
return {
seen_init: seenInit,
tpl_init_count: tplInitCount,
template_wrapper_in_dom: tplTagInDom,
seen_after_false: document.getElementById('seen-p') !== null,
tpl_after_false_count: document.querySelectorAll('#sec-basic .tpl-child').length
};
}""")
exp1 = {
"seen_init": True,
"tpl_init_count": 3,
"template_wrapper_in_dom": 0,
"seen_after_false": False,
"tpl_after_false_count": 0,
}
cases.append({
"name": "v_if_element_and_template_group",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: v-if / v-else binary branch switching
res2 = page.evaluate("""() => {
const highText = document.querySelector('#sec-else .branch-else').textContent.trim();
const highNodes = document.querySelectorAll('#sec-else .branch-else').length;
window.vm.score = 0.31;
const lowText = document.querySelector('#sec-else .branch-else').textContent.trim();
const lowNodes = document.querySelectorAll('#sec-else .branch-else').length;
return {
score_072_text: highText,
score_072_nodes: highNodes,
score_031_text: lowText,
score_031_nodes: lowNodes
};
}""")
exp2 = {
"score_072_text": "Sorry",
"score_072_nodes": 1,
"score_031_text": "Not sorry",
"score_031_nodes": 1,
}
cases.append({
"name": "v_if_v_else_branch_switch",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: v-else-if multi-branch chain (A, B, C, fallback)
res3 = page.evaluate("""() => {
const out = {};
for (const t of ['A', 'B', 'C', 'D']) {
window.vm.type = t;
const nodes = document.querySelectorAll('#sec-elseif .branch-type');
out[t] = { text: nodes[0].textContent.trim(), count: nodes.length };
}
return out;
}""")
exp3 = {
"A": {"text": "A", "count": 1},
"B": {"text": "B", "count": 1},
"C": {"text": "C", "count": 1},
"D": {"text": "Not A/B/C", "count": 1},
}
cases.append({
"name": "v_else_if_chain_all_branches",
"passed": res3 == exp3,
"expected": exp3,
"actual": res3,
})
# Case 4: v-show (CSS display toggle) vs v-if (DOM removal)
res4 = page.evaluate("""() => {
const showDisplayTrue = getComputedStyle(document.getElementById('show-h1')).display;
const ifExistsTrue = document.getElementById('if-h1') !== null;
window.vm.showFlag = false;
const showElFalse = document.getElementById('show-h1');
return {
show_display_true: showDisplayTrue,
if_exists_true: ifExistsTrue,
show_in_dom_false: showElFalse !== null,
show_display_false: getComputedStyle(showElFalse).display,
if_exists_false: document.getElementById('if-h1') !== null
};
}""")
exp4 = {
"show_display_true": "block",
"if_exists_true": True,
"show_in_dom_false": True,
"show_display_false": "none",
"if_exists_false": False,
}
cases.append({
"name": "v_show_css_display_vs_v_if",
"passed": res4 == exp4,
"expected": exp4,
"actual": res4,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
频繁切换显隐应优先用 `v-show`,它仅改写 CSS `display` 避免反复销毁重建 DOM 与子组件;初始条件为假且很少变更的区块应优先用 `v-if`,它具备惰性渲染特性,可减少初始渲染开销。