"""Offline Chromium runtime verification for Vue 2 Chapter 22: vue-examples."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def make_case(name, expected, actual):
return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
# Case 1: Navigation menu example
page.set_content("""
<!doctype html>
<html><body>
<div id="main">
<nav id="nav" class="home">
<a href="#home" data-item="home">Home</a>
<a href="#projects" data-item="projects">Projects</a>
<a href="#services" data-item="services">Services</a>
<a href="#contact" data-item="contact">Contact</a>
</nav>
<p id="choice">您选择了 <b>home 菜单</b></p>
</div>
<script>
let active = 'home';
const nav = document.getElementById('nav');
nav.addEventListener('click', (e) => {
e.preventDefault();
if (e.target.dataset.item) {
active = e.target.dataset.item;
nav.className = active;
document.getElementById('choice').innerHTML = `您选择了 <b>${active} 菜单</b>`;
}
});
</script>
</body></html>
""")
init_nav = page.locator("#nav").get_attribute("class")
page.click("a[data-item='services']")
actual1 = {
"initialClass": init_nav,
"afterClickClass": page.locator("#nav").get_attribute("class"),
"choiceText": page.locator("#choice").inner_text(),
"hashRemainedEmpty": page.evaluate("location.hash === ''"),
}
expected1 = {
"initialClass": "home",
"afterClickClass": "services",
"choiceText": "您选择了 services 菜单",
"hashRemainedEmpty": True,
}
cases.append(make_case("nav_menu_example", expected1, actual1))
# Case 2: Inline text editor example (v-cloak, .stop, v-if, v-model)
page.set_content("""
<!doctype html>
<html><body>
<div id="main" style="padding:20px;">
<div id="outside">空白区域</div>
<div id="tooltip-host"></div>
<p id="editable-p">点我,并编辑内容。</p>
</div>
<script>
let show_tooltip = false;
let text_content = '点我,并编辑内容。';
const host = document.getElementById('tooltip-host');
const pEl = document.getElementById('editable-p');
function render() {
pEl.textContent = text_content;
host.innerHTML = '';
if (show_tooltip) {
const box = document.createElement('div');
box.className = 'tooltip';
box.addEventListener('click', (e) => e.stopPropagation());
const inp = document.createElement('input');
inp.id = 'editor-input';
inp.type = 'text';
inp.value = text_content;
inp.addEventListener('input', (e) => {
text_content = e.target.value;
pEl.textContent = text_content;
});
box.appendChild(inp);
host.appendChild(box);
}
}
document.getElementById('main').addEventListener('click', () => {
show_tooltip = false;
render();
});
pEl.addEventListener('click', (e) => {
e.stopPropagation();
show_tooltip = !show_tooltip;
render();
});
</script>
</body></html>
""")
init_tip = page.locator(".tooltip").count()
page.click("#editable-p")
open_tip = page.locator(".tooltip").count()
page.fill("#editor-input", "已编辑的新文本")
page.click("#outside")
closed_tip = page.locator(".tooltip").count()
actual2 = {
"initialTooltipCount": init_tip,
"openedTooltipCount": open_tip,
"closedTooltipCount": closed_tip,
"finalText": page.locator("#editable-p").inner_text(),
}
expected2 = {
"initialTooltipCount": 0,
"openedTooltipCount": 1,
"closedTooltipCount": 0,
"finalText": "已编辑的新文本",
}
cases.append(make_case("inline_text_editor_example", expected2, actual2))
# Case 3: Order list with currency filter and running total
page.set_content("""
<!doctype html>
<html><body>
<ul id="svc-list"></ul>
<div class="total">Total: <span id="total-val"></span></div>
<script>
const currency = v => '$' + v.toFixed(2);
const services = [
{ name: 'Web Development', price: 300, active: true },
{ name: 'Design', price: 400, active: false },
{ name: 'Integration', price: 250, active: false },
{ name: 'Training', price: 220, active: false },
];
function total() {
return services.reduce((acc, s) => acc + (s.active ? s.price : 0), 0);
}
function render() {
const ul = document.getElementById('svc-list');
ul.innerHTML = '';
services.forEach((s, idx) => {
const li = document.createElement('li');
li.id = 'svc-' + idx;
li.className = s.active ? 'active' : '';
li.textContent = `${s.name} ${currency(s.price)}`;
li.addEventListener('click', () => { s.active = !s.active; render(); });
ul.appendChild(li);
});
document.getElementById('total-val').textContent = currency(total());
}
render();
</script>
</body></html>
""")
t0 = page.locator("#total-val").inner_text()
page.click("#svc-1")
t1 = page.locator("#total-val").inner_text()
page.click("#svc-3")
t2 = page.locator("#total-val").inner_text()
page.click("#svc-0")
t3 = page.locator("#total-val").inner_text()
actual3 = {"initial": t0, "plusDesign": t1, "plusTraining": t2, "minusWebDev": t3}
expected3 = {"initial": "$300.00", "plusDesign": "$700.00", "plusTraining": "$920.00", "minusWebDev": "$620.00"}
cases.append(make_case("order_list_currency_total_example", expected3, actual3))
# Case 4: Search page with computed filteredArticles
page.set_content("""
<!doctype html>
<html><body>
<input id="search-in" type="text" placeholder="输入搜索内容" />
<ul id="article-list"></ul>
<script>
const articles = [
{ title: 'What You Need To Know About CSS Variables' },
{ title: 'Freebie: 4 Great Looking Pricing Tables' },
{ title: '20 Interesting JavaScript and CSS Libraries for February 2016' },
{ title: 'Quick Tip: The Easiest Way To Make Responsive Headers' },
{ title: 'Learn SQL In 20 Minutes' },
{ title: 'Creating Your First Desktop App With HTML, JS and Electron' },
];
function filteredArticles(q) {
if (!q) return articles;
const norm = q.trim().toLowerCase();
return articles.filter(item => item.title.toLowerCase().indexOf(norm) !== -1);
}
function render(q) {
const ul = document.getElementById('article-list');
ul.innerHTML = '';
filteredArticles(q).forEach(a => {
const li = document.createElement('li');
li.textContent = a.title;
ul.appendChild(li);
});
}
document.getElementById('search-in').addEventListener('input', (e) => render(e.target.value));
render('');
</script>
</body></html>
""")
c_all = page.locator("#article-list li").count()
page.fill("#search-in", " CSS ")
c_css = page.locator("#article-list li").count()
page.fill("#search-in", "SQL")
c_sql = page.locator("#article-list li").count()
page.fill("#search-in", "nonexistent")
c_none = page.locator("#article-list li").count()
actual4 = {"all": c_all, "css": c_css, "sql": c_sql, "none": c_none}
expected4 = {"all": 6, "css": 2, "sql": 1, "none": 0}
cases.append(make_case("search_filter_list_example", expected4, actual4))
# Case 5: Layout switch (grid vs list)
page.set_content("""
<!doctype html>
<html><body>
<div class="bar">
<a id="btn-list" class="list-icon">list</a>
<a id="btn-grid" class="grid-icon active">grid</a>
</div>
<div id="layout-host"></div>
<script>
let layout = 'grid';
const items = ['HTML 教程', 'CSS 教程', 'JS 教程', 'SQL 教程', 'Ajax 教程', 'Python 教程'];
function render() {
document.getElementById('btn-list').className = 'list-icon' + (layout === 'list' ? ' active' : '');
document.getElementById('btn-grid').className = 'grid-icon' + (layout === 'grid' ? ' active' : '');
const host = document.getElementById('layout-host');
host.innerHTML = '';
const ul = document.createElement('ul');
ul.className = layout;
items.forEach(title => {
const li = document.createElement('li');
if (layout === 'grid') {
const box = document.createElement('span');
box.className = 'thumb-large';
li.appendChild(box);
} else {
const box = document.createElement('span');
box.className = 'thumb-small';
const p = document.createElement('p');
p.textContent = title;
li.appendChild(box);
li.appendChild(p);
}
ul.appendChild(li);
});
host.appendChild(ul);
}
document.getElementById('btn-list').addEventListener('click', () => { layout = 'list'; render(); });
document.getElementById('btn-grid').addEventListener('click', () => { layout = 'grid'; render(); });
render();
</script>
</body></html>
""")
init_grid = page.locator("ul.grid li").count()
init_list = page.locator("ul.list li").count()
page.click("#btn-list")
after_grid = page.locator("ul.grid li").count()
after_list = page.locator("ul.list li").count()
list_titles = page.locator("ul.list li p").all_inner_texts()
actual5 = {
"initialGridCount": init_grid,
"initialListCount": init_list,
"afterSwitchGridCount": after_grid,
"afterSwitchListCount": after_list,
"listTitlesCount": len(list_titles),
"firstTitle": list_titles[0],
}
expected5 = {
"initialGridCount": 6,
"initialListCount": 0,
"afterSwitchGridCount": 0,
"afterSwitchListCount": 6,
"listTitlesCount": 6,
"firstTitle": "HTML 教程",
}
cases.append(make_case("layout_toggle_grid_list_example", expected5, actual5))
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-examples-lab/explore-vue-examples.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-vue-examples.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a784.zip