"""Offline Playwright Chromium lab for Vue3 Ch40: Blog template syntax rendering."""
import json
from playwright.sync_api import sync_playwright
HTML = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>Vue3 Blog Template Syntax Lab</title>
<style>
body { font-family: system-ui, sans-serif; margin: 0; background: #f5f5f5; color: #333; }
.home { max-width: 960px; margin: 0 auto; padding: 20px; }
.article-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 24px; }
.article-card { background: #fff; border-radius: 12px; overflow: hidden; }
.card-category { display: inline-block; padding: 2px 10px; background: #e8f5e9; color: #42b883; border-radius: 12px; font-size: 12px; }
.card-cover { width: 100%; height: 120px; object-fit: cover; display: block; }
.active { border: 1px solid #42b883; }
.text-bold { font-weight: 700; }
</style>
</head>
<body>
<section id="sec-mustache">
<h1 id="m-title"></h1>
<p id="m-author"></p>
<p id="m-date"></p>
<p id="m-escape"></p>
</section>
<section id="sec-vbind">
<img id="b-img" />
<a id="b-link">阅读全文</a>
<div id="b-box">动态 class 测试</div>
</section>
<section class="home" id="sec-home">
<h2 class="section-title">最新文章</h2>
<div id="home-body"></div>
</section>
<section id="sec-key-demo">
<div id="list-by-id"></div>
<div id="list-by-index"></div>
</section>
<section id="sec-cond">
<div id="state-host"></div>
<div id="vif-host"></div>
<div id="vshow-box">v-show 面板</div>
</section>
<script>
// Inline SVG data URI so zero external requests are made
const SVG_COVER = 'data:image/svg+xml;utf8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="300" height="120"><rect width="300" height="120" fill="#e8f5e9"/></svg>');
function formatCnDate(iso) {
const [y, m, d] = iso.split('-');
return `${y}/${Number(m)}/${Number(d)}`;
}
// 1. Mustache {{ }} interpolation (textContent only, safe escaping) + v-bind
const blogTitle = '蓝色天空前端笔记';
const author = '小明';
const rawSnippet = '<strong>原样文本</strong>';
document.getElementById('m-title').textContent = blogTitle;
document.getElementById('m-author').textContent = `作者:${author}`;
document.getElementById('m-date').textContent = `当前时间:${formatCnDate('2024-05-15')}`;
document.getElementById('m-escape').textContent = rawSnippet;
const coverUrl = SVG_COVER;
const linkUrl = '/post/1';
const isActive = true;
const imgEl = document.getElementById('b-img');
imgEl.setAttribute('src', coverUrl);
imgEl.setAttribute('alt', '文章封面');
document.getElementById('b-link').setAttribute('href', linkUrl);
const boxEl = document.getElementById('b-box');
const classMap = { active: isActive, 'text-bold': true };
for (const [cls, on] of Object.entries(classMap)) boxEl.classList.toggle(cls, Boolean(on));
// 2. Complete blog homepage v-for + v-if/v-else
const articles = [
{ id: 1, title: 'Vue3 入门完全指南', summary: '组合式 API 核心概念。', date: '2024-05-10', category: 'Vue', cover: SVG_COVER },
{ id: 2, title: 'JavaScript 异步编程详解', summary: 'Promise、async/await 与事件循环。', date: '2024-05-08', category: 'JavaScript', cover: SVG_COVER },
{ id: 3, title: 'CSS Grid 布局实战', summary: '响应式网格布局实践。', date: '2024-05-05', category: 'CSS', cover: SVG_COVER }
];
function renderHome(list) {
const host = document.getElementById('home-body');
if (!list.length) {
host.innerHTML = '<p class="empty-tip">还没有文章,敬请期待。</p>';
return;
}
const grid = document.createElement('div');
grid.className = 'article-grid';
for (const a of list) {
const card = document.createElement('div');
card.className = 'article-card';
card.dataset.key = String(a.id);
card.innerHTML = `
<img src="${a.cover}" alt="${a.title}" class="card-cover" />
<div class="card-content">
<span class="card-category">${a.category}</span>
<h3 class="card-title">${a.title}</h3>
<p class="card-summary">${a.summary}</p>
<span class="card-date">${a.date}</span>
</div>`;
grid.appendChild(card);
}
host.innerHTML = '';
host.appendChild(grid);
}
renderHome(articles);
// 3. v-for key=id vs key=index DOM reuse comparison
let keyItems = [
{ id: 1, title: 'Vue3 入门' },
{ id: 2, title: 'CSS 布局' }
];
const idNodes = new Map();
const idxNodes = new Map();
function patchList(containerId, cache, mode) {
const host = document.getElementById(containerId);
const frag = document.createDocumentFragment();
keyItems.forEach((item, idx) => {
const k = mode === 'id' ? String(item.id) : String(idx);
let row = cache.get(k);
if (!row) {
row = document.createElement('div');
row.className = 'k-row';
const label = document.createElement('span');
const inp = document.createElement('input');
row.append(label, inp);
cache.set(k, row);
}
row.dataset.itemId = String(item.id);
row.querySelector('span').textContent = item.title;
frag.appendChild(row);
});
host.innerHTML = '';
host.appendChild(frag);
}
patchList('list-by-id', idNodes, 'id');
patchList('list-by-index', idxNodes, 'index');
window.__prependAndCheckKeys = function() {
document.querySelector('#list-by-id .k-row input').value = 'Vue笔记';
document.querySelector('#list-by-index .k-row input').value = 'Vue笔记';
keyItems = [{ id: 99, title: '置顶新文' }, ...keyItems];
patchList('list-by-id', idNodes, 'id');
patchList('list-by-index', idxNodes, 'index');
const idList = [...document.querySelectorAll('#list-by-id .k-row')].map(r => ({
id: Number(r.dataset.itemId),
inputVal: r.querySelector('input').value
}));
const idxList = [...document.querySelectorAll('#list-by-index .k-row')].map(r => ({
id: Number(r.dataset.itemId),
inputVal: r.querySelector('input').value
}));
return { idList, idxList };
};
// 4. v-if / v-else-if / v-else 3-state UI & v-if vs v-show
window.__testConditional = function() {
const host = document.getElementById('state-host');
function renderState(isLoading, items) {
if (isLoading) host.innerHTML = '<p class="st">加载中,请稍候...</p>';
else if (items.length > 0) host.innerHTML = `<div class="st">${items.map(x => `<div class="mini-card">${x.title}</div>`).join('')}</div>`;
else host.innerHTML = '<p class="st">还没有文章,敬请期待。</p>';
}
renderState(true, []);
const s1 = host.textContent.trim();
renderState(false, [{ id: 1, title: 'Vue3 入门' }, { id: 2, title: 'React 对比' }]);
const s2Count = host.querySelectorAll('.mini-card').length;
renderState(false, []);
const s3 = host.textContent.trim();
// v-if=false removes DOM node; v-show=false keeps DOM node with display:none
const vifHost = document.getElementById('vif-host');
vifHost.innerHTML = '<div id="vif-box">v-if 面板</div>';
vifHost.innerHTML = ''; // toggled to false
const vshowBox = document.getElementById('vshow-box');
vshowBox.style.display = 'none';
return {
loadingText: s1,
loadedCardCount: s2Count,
emptyText: s3,
vifNodeExistsWhenFalse: document.getElementById('vif-box') !== null,
vshowNodeExistsWhenFalse: document.getElementById('vshow-box') !== null,
vshowDisplayWhenFalse: getComputedStyle(vshowBox).display
};
};
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1280, "height": 800})
page.set_content(HTML, wait_until="domcontentloaded")
# Case 1: Mustache {{ }} interpolation & v-bind / : attribute binding
act1 = page.evaluate("""() => ({
title: document.getElementById('m-title').textContent,
author: document.getElementById('m-author').textContent,
date: document.getElementById('m-date').textContent,
escapedHtmlHasStrongChild: document.querySelector('#m-escape strong') !== null,
escapedText: document.getElementById('m-escape').textContent,
imgAlt: document.getElementById('b-img').getAttribute('alt'),
linkHref: document.getElementById('b-link').getAttribute('href'),
boxClasses: [...document.getElementById('b-box').classList].sort()
})""")
exp1 = {
"title": "蓝色天空前端笔记",
"author": "作者:小明",
"date": "当前时间:2024/5/15",
"escapedHtmlHasStrongChild": False,
"escapedText": "<strong>原样文本</strong>",
"imgAlt": "文章封面",
"linkHref": "/post/1",
"boxClasses": ["active", "text-bold"],
}
cases.append({"name": "interpolation_and_vbind_attrs", "expected": exp1, "actual": act1, "passed": act1 == exp1})
# Case 2: Complete blog homepage v-for cards, categories, dates, CSS Grid
act2 = page.evaluate("""() => {
const grid = document.querySelector('.article-grid');
const badge = document.querySelector('.card-category');
return {
gridDisplay: getComputedStyle(grid).display,
cardCount: document.querySelectorAll('.article-card').length,
categories: [...document.querySelectorAll('.card-category')].map(el => el.textContent),
dates: [...document.querySelectorAll('.card-date')].map(el => el.textContent),
badgeColor: getComputedStyle(badge).color,
badgeBg: getComputedStyle(badge).backgroundColor
};
}""")
exp2 = {
"gridDisplay": "grid",
"cardCount": 3,
"categories": ["Vue", "JavaScript", "CSS"],
"dates": ["2024-05-10", "2024-05-08", "2024-05-05"],
"badgeColor": "rgb(66, 184, 131)",
"badgeBg": "rgb(232, 245, 233)",
}
cases.append({"name": "vfor_blog_homepage_cards", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: v-for :key="article.id" vs index state preservation
act3 = page.evaluate("window.__prependAndCheckKeys()")
exp3 = {
"idList": [
{"id": 99, "inputVal": ""},
{"id": 1, "inputVal": "Vue笔记"},
{"id": 2, "inputVal": ""},
],
"idxList": [
{"id": 99, "inputVal": "Vue笔记"},
{"id": 1, "inputVal": ""},
{"id": 2, "inputVal": ""},
],
}
cases.append({"name": "vfor_key_id_vs_index_state", "expected": exp3, "actual": act3, "passed": act3 == exp3})
# Case 4: v-if/v-else-if/v-else 3-state flow & v-if vs v-show DOM check
act4 = page.evaluate("window.__testConditional()")
exp4 = {
"loadingText": "加载中,请稍候...",
"loadedCardCount": 2,
"emptyText": "还没有文章,敬请期待。",
"vifNodeExistsWhenFalse": False,
"vshowNodeExistsWhenFalse": True,
"vshowDisplayWhenFalse": "none",
}
cases.append({"name": "vif_three_states_and_vshow_dom", "expected": exp4, "actual": act4, "passed": act4 == exp4})
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/vue3-blog-template-syntax-lab/explore-blog-template-syntax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-template-syntax.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a808.zip