在线代码实验室
离线 Chromium 实测 BlogCard defineProps 只读保护、CategoryFilter defineEmits 与 HomeView 整合
"""Offline Playwright Chromium lab for Vue 3 Ch 42: component splitting, defineProps & defineEmits."""
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")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Components Props Emit Lab</title>
<style>
.filter-bar button.active { background: #42b883; color: #fff; }
.article-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; }
</style>
</head>
<body>
<div id="app"></div>
<script>
// Minimal component runner mimicking Vue 3 defineProps (readonly one-way flow) & defineEmits
const propWarnings = [];
const emittedEvents = [];
function createReadonlyProps(schema, rawProps) {
const checked = {};
for (const [key, ctor] of Object.entries(schema)) {
const val = rawProps[key];
if (ctor && val !== undefined) {
const ok =
(ctor === String && typeof val === 'string') ||
(ctor === Number && typeof val === 'number') ||
(ctor === Array && Array.isArray(val));
if (!ok) propWarnings.push(`type-mismatch:${key}`);
}
checked[key] = val;
}
return new Proxy(checked, {
set(_t, prop) {
propWarnings.push(`readonly-prop:${String(prop)}`);
return true; // swallow mutation to preserve one-way data flow
}
});
}
function createEmit(declared, handlers) {
return (eventName, ...args) => {
if (!declared.includes(eventName)) {
throw new Error(`Undeclared emit: ${eventName}`);
}
emittedEvents.push({ event: eventName, payload: args[0] });
if (handlers[eventName]) handlers[eventName](...args);
};
}
// Component 1: NavBar
function renderNavBar() {
const header = document.createElement('header');
header.className = 'navbar';
header.innerHTML = `<a href="/" class="logo">BlueSky Blog</a><nav><a href="/">首页</a><a href="#about">关于</a></nav>`;
return header;
}
// Component 2: BlogCard (defineProps)
function renderBlogCard(rawProps) {
const props = createReadonlyProps(
{ title: String, summary: String, date: String, category: String },
rawProps
);
// Attempt illegal direct mutation inside child to verify one-way data flow guard
if (rawProps.__testMutate) {
props.title = 'ILLEGAL_CHILD_WRITE';
}
const card = document.createElement('div');
card.className = 'card';
card.innerHTML = `<span class="tag">${props.category}</span><h3>${props.title}</h3><p>${props.summary}</p><span class="date">${props.date}</span>`;
return card;
}
// Component 3: CategoryFilter (defineProps + defineEmits)
function renderCategoryFilter(rawProps, handlers) {
const props = createReadonlyProps(
{ categories: Array, activeCategory: String },
rawProps
);
const emit = createEmit(['update-category'], handlers);
const bar = document.createElement('div');
bar.className = 'filter-bar';
for (const cat of props.categories) {
const btn = document.createElement('button');
btn.textContent = cat;
btn.dataset.cat = cat;
if (props.activeCategory === cat) btn.className = 'active';
btn.addEventListener('click', () => emit('update-category', cat));
bar.appendChild(btn);
}
return bar;
}
// Parent View: HomeView
const state = {
articles: [
{ id: 1, title: 'Vue3 入门完全指南', summary: '从零开始学习 Vue3 组合式 API', date: '2024-05-10', category: 'Vue' },
{ id: 2, title: 'JS 异步编程详解', summary: '搞懂 Promise 和 async/await', date: '2024-05-08', category: 'JavaScript' },
{ id: 3, title: 'CSS Grid 布局实战', summary: '用 Grid 实现响应式布局', date: '2024-05-05', category: 'CSS' },
{ id: 4, title: 'Vue3 响应式原理', summary: '深入理解 ref 和 reactive', date: '2024-05-03', category: 'Vue' },
{ id: 5, title: 'Flexbox 完全指南', summary: '一文学会弹性布局', date: '2024-05-01', category: 'CSS' }
],
extraEmptyCategory: false,
activeCategory: '全部'
};
function getCategories() {
const cats = ['全部', ...new Set(state.articles.map((a) => a.category))];
if (state.extraEmptyCategory) cats.push('TypeScript');
return cats;
}
function getFilteredArticles() {
if (state.activeCategory === '全部') return state.articles;
return state.articles.filter((a) => a.category === state.activeCategory);
}
function renderApp(testMutateFirstCard = false) {
const root = document.getElementById('app');
root.innerHTML = '';
root.appendChild(renderNavBar());
const home = document.createElement('div');
home.className = 'home';
const h2 = document.createElement('h2');
h2.className = 'section-title';
h2.textContent = '最新文章';
home.appendChild(h2);
home.appendChild(
renderCategoryFilter(
{ categories: getCategories(), activeCategory: state.activeCategory },
{
'update-category': (cat) => {
state.activeCategory = cat;
renderApp(false);
}
}
)
);
const list = getFilteredArticles();
if (list.length === 0) {
const empty = document.createElement('p');
empty.className = 'empty-tip';
empty.textContent = '该分类下暂无文章';
home.appendChild(empty);
} else {
const grid = document.createElement('div');
grid.className = 'article-grid';
list.forEach((article, idx) => {
grid.appendChild(
renderBlogCard({
title: article.title,
summary: article.summary,
date: article.date,
category: article.category,
__testMutate: testMutateFirstCard && idx === 0
})
);
});
home.appendChild(grid);
}
root.appendChild(home);
}
renderApp(true);
window.__compLab = {
enableEmptyCategory() {
state.extraEmptyCategory = true;
renderApp(false);
},
getReport() {
return {
propWarnings: [...propWarnings],
emittedEvents: [...emittedEvents],
activeCategory: state.activeCategory,
parentFirstTitle: state.articles[0].title
};
}
};
</script>
</body>
</html>
"""
def main():
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
page.set_content(HTML)
# Case 1: defineProps renders BlogCard & blocks child prop mutation
initial_cards = page.eval_on_selector_all(".card h3", "els => els.map(e => e.textContent)")
first_tag = page.text_content(".card .tag")
first_date = page.text_content(".card .date")
rep1 = page.evaluate("window.__compLab.getReport()")
# Case 2: defineEmits CategoryFilter -> HomeView
page.click('.filter-bar button[data-cat="Vue"]')
vue_cards = page.eval_on_selector_all(".card h3", "els => els.map(e => e.textContent)")
vue_active = page.text_content(".filter-bar button.active")
page.click('.filter-bar button[data-cat="JavaScript"]')
js_cards = page.eval_on_selector_all(".card h3", "els => els.map(e => e.textContent)")
rep2 = page.evaluate("window.__compLab.getReport()")
# Case 3: NavBar & HomeView integration
nav_logo = page.text_content(".navbar .logo")
nav_links = page.eval_on_selector_all(".navbar nav a", "els => els.map(e => e.textContent)")
page.click('.filter-bar button[data-cat="全部"]')
restored_count = page.locator(".card").count()
# Case 4: Empty category fallback
page.evaluate("window.__compLab.enableEmptyCategory()")
page.click('.filter-bar button[data-cat="TypeScript"]')
empty_tip = page.text_content(".empty-tip")
empty_cards = page.locator(".card").count()
finally:
browser.close()
actuals = {
"define_props_blog_card_and_readonly": {
"initial_card_count": len(initial_cards),
"first_title": initial_cards[0],
"first_tag": first_tag,
"first_date": first_date,
"parent_title_unchanged": rep1["parentFirstTitle"],
"prop_warnings": rep1["propWarnings"],
},
"define_emits_category_filter_upward": {
"vue_active": vue_active,
"vue_cards": vue_cards,
"js_cards": js_cards,
"emitted_events": rep2["emittedEvents"],
},
"navbar_and_home_integration": {
"nav_logo": nav_logo,
"nav_links": nav_links,
"restored_count": restored_count,
},
"empty_category_fallback_dom": {
"empty_tip": empty_tip,
"empty_card_count": empty_cards,
},
}
expected = {
"define_props_blog_card_and_readonly": {
"initial_card_count": 5,
"first_title": "Vue3 入门完全指南",
"first_tag": "Vue",
"first_date": "2024-05-10",
"parent_title_unchanged": "Vue3 入门完全指南",
"prop_warnings": ["readonly-prop:title"],
},
"define_emits_category_filter_upward": {
"vue_active": "Vue",
"vue_cards": ["Vue3 入门完全指南", "Vue3 响应式原理"],
"js_cards": ["JS 异步编程详解"],
"emitted_events": [
{"event": "update-category", "payload": "Vue"},
{"event": "update-category", "payload": "JavaScript"},
],
},
"navbar_and_home_integration": {
"nav_logo": "BlueSky Blog",
"nav_links": ["首页", "关于"],
"restored_count": 5,
},
"empty_category_fallback_dom": {
"empty_tip": "该分类下暂无文章",
"empty_card_count": 0,
},
}
cases = [
{"name": k, "expected": expected[k], "actual": actuals[k], "passed": actuals[k] == expected[k]}
for k in expected
]
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vue3-blog-components-props-emit-lab/explore-blog-components-props-emit.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-components-props-emit.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a802.zip
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip