"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vue2-vue-if-lab/explore-vue-if.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-vue-if.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a786.zip
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip