Vue.js 实例
综合运用事件修饰符、v-cloak、v-if、v-for、过滤器与计算属性,在离线 Chromium 中逐一验证导航菜单、行内编辑、订单计价、实时搜索与布局切换 5 个经典交互应用。
学完这一章,你能够
- 综合运用事件修饰符、v-cloak、v-if、v-for、过滤器与计算属性,在离线 Chromium 中逐一验证导航菜单、行内编辑、订单计价、实时搜索与布局切换 5 个经典交互应用。
导航菜单与行内文本编辑实例
综合实例可帮助串联指令、样式绑定、事件修饰符与计算属性。在导航菜单实例中,`<nav>` 同时绑定 `:class="active"` 与 `v-on:click.prevent` 阻止 `<a>` 默认锚点跳转,点击各菜单项调用 `makeActive(item)` 即可切换高亮类与提示文本。本站离线 Chromium 实测初始 `active` 类为 `home`,点击 `Services` 后 `<nav>` 类变为 `services`、提示显示“您选择了 services 菜单”,且页面 `location.hash` 保持为空未发生跳转。
在行内文本编辑实例中,外层容器使用 `v-cloak` 隐藏编译前模板并监听 `v-on:click="hideTooltip"`;内部编辑浮层以 `v-if="show_tooltip"` 控制显隐并用 `v-on:click.stop` 阻止冒泡,`<p>` 同样以 `v-on:click.stop="toggleTooltip"` 切换浮层,从而实现“点文本弹出输入框、点空白处自动收起”。本站离线 Chromium 实测点击文本后浮层数量由 `0` 变 `1`,输入“已编辑的新文本”再点击空白区后浮层收起为 `0`,段落保留最新文本。
订单列表计价与实时搜索过滤实例
订单列表实例结合 `v-for`、动态类 `:class="{ active: service.active }"`、点击切换 `toggleActive(service)`、求和方法 `total()` 与自定义货币过滤器 `Vue.filter('currency', v => '$' + v.toFixed(2))` 动态汇总选中服务费用(注意 Vue 3 已移除过滤器语法,推荐改用方法或计算属性)。本站离线 Chromium 实测初始仅选中 Web Development(300)总计 `$300.00`,依次勾选 Design(+400)得 `$700.00`、勾选 Training(+220)得 `$920.00`、取消 Web Development(-300)得 `$620.00`。
搜索页面实例将输入框通过 `v-model="searchString"` 绑定,并借助计算属性 `filteredArticles` 执行 `trim().toLowerCase()` 后按子串大小写不敏感筛选文章数组,空关键词时原样返回全部条目。本站离线 Chromium 实测 6 篇条目在空查询时显示 `6` 项,输入带空格的 `" CSS "` 筛出 `2` 项,输入 `"SQL"` 筛出 `1` 项,输入不匹配词筛出 `0` 项。
网格与列表布局切换实例
切换布局实例通过状态变量 `layout`(取值 `'grid'` 或 `'list'`)同时驱动顶部切换按钮的 `active` 高亮类与下方两套互斥 `v-if` 列表模板:网格模式渲染大图无标题卡片,列表模式渲染缩略图配标题段落。本站离线 Chromium 实测初始 `'grid'` 态仅存在 6 项 `ul.grid`(`ul.list` 为 `0` 项),点击列表按钮后 `ul.grid` 移除为 `0` 项,`ul.list` 渲染出 6 项且首条标题为“HTML 教程”。
离线 Chromium 验证 5 个经典 Vue 2 综合交互应用
"""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()
- 核对导航菜单防跳转切换、行内编辑冒泡控制、订单总价 $300→$700→$920→$620、搜索过滤 6→2→1→0 及 grid/list 布局互斥切换。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:bda3391a17602f6cee28ea766c9edac428182ffa26740fd031aa50d82ce6d22b
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:80bc754b5f91c5b4e9c44a37b8896ff4ec926ab7c3b260233db49d24b841ae8f
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
行内文本编辑实例中,为什么要在 `.tooltip` 容器和 `<p>` 标签上都添加 `.stop` 修饰符?
展开参考解答
因为外层 `#main` 容器绑定了点击关闭浮层的 `hideTooltip`,若不阻止内部点击事件向上冒泡,点击 `<p>` 打开浮层或点击输入框编辑内容时事件都会冒泡到外层并立刻把浮层再次关闭。