"""Offline Playwright Chromium lab for Vue 3 Ch 43: Vue Router SPA navigation, dynamic params & 404."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
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 Router Lab</title>
</head>
<body>
<header class="navbar">
<a href="/" data-router-link="/" class="logo">BlueSky Blog</a>
<nav>
<a href="/" data-router-link="/">首页</a>
<a href="/post/999" data-router-link="/post/999" id="link-404">不存在文章</a>
</nav>
</header>
<main id="router-view"></main>
<script>
window.__mountNonce = 'SPA-NONCE-43';
let lazyLoadCount = 0;
const articles = [
{
id: 1,
title: 'Vue3 入门完全指南',
summary: '从零开始学习 Vue3 组合式 API',
category: 'Vue',
date: '2024-05-10',
content: '<h2>为什么学 Vue3?</h2><p>Vue3 是目前最流行的前端框架之一。</p><h2>ref 与 reactive</h2><p>推荐统一使用 ref 管理状态。</p>'
},
{
id: 2,
title: 'JS 异步编程详解',
summary: '搞懂 Promise 和 async/await',
category: 'JavaScript',
date: '2024-05-08',
content: '<h2>什么是异步?</h2><p>JS 是单线程的,异步操作不会阻塞主线程。</p>'
}
];
function HomeView() {
return `
<div class="home">
<h1>最新文章</h1>
<div class="article-grid">
${articles
.map(
(a) => `
<a href="/post/${a.id}" data-router-link="/post/${a.id}" class="card-link" data-id="${a.id}">
<div class="card">
<span class="tag">${a.category}</span>
<h3>${a.title}</h3>
<p>${a.summary}</p>
</div>
</a>`
)
.join('')}
</div>
</div>`;
}
function PostView(route) {
const rawParam = route.params.id;
const id = Number(rawParam);
const article = articles.find((a) => a.id === id);
window.__lastRouteParam = { raw: rawParam, rawType: typeof rawParam, numeric: id };
if (!article) {
return `
<div class="post-view">
<div class="not-found">
<h2>文章不存在</h2>
<p class="not-found-msg">找不到 ID 为 ${id} 的文章</p>
<a href="/" data-router-link="/" class="back-link">返回首页</a>
</div>
</div>`;
}
return `
<div class="post-view">
<article>
<span class="category-tag">${article.category}</span>
<h1>${article.title}</h1>
<time>${article.date}</time>
<div class="content">${article.content}</div>
<a href="/" data-router-link="/" class="back-link">← 返回首页</a>
</article>
</div>`;
}
const routes = [
{ path: '/', name: 'home', component: HomeView },
{
path: '/post/:id',
name: 'post',
component: async () => {
lazyLoadCount++;
return PostView;
}
}
];
function matchRoute(pathname) {
if (pathname === '/') return { route: routes[0], params: {} };
const m = pathname.match(/^\/post\/([^/]+)$/);
if (m) return { route: routes[1], params: { id: decodeURIComponent(m[1]) } };
return { route: routes[1], params: { id: 'NaN' } };
}
async function renderPath(pathname) {
const matched = matchRoute(pathname);
const compOrLoader = matched.route.component;
const viewFn = matched.route.name === 'post' ? await compOrLoader() : compOrLoader;
const routeObj = { path: pathname, name: matched.route.name, params: matched.params };
document.getElementById('router-view').innerHTML = viewFn(routeObj);
}
async function push(pathname) {
window.history.pushState({}, '', pathname);
await renderPath(pathname);
}
// Intercept declarative RouterLink clicks (no full page reload)
document.addEventListener('click', (e) => {
const link = e.target.closest('a[data-router-link]');
if (!link) return;
e.preventDefault();
push(link.getAttribute('data-router-link'));
});
window.addEventListener('popstate', () => {
renderPath(window.location.pathname);
});
// Compare createWebHistory vs createWebHashHistory URL format
window.__routerLab = {
testHashMode(id) {
window.location.hash = `#/post/${id}`;
return window.location.hash;
},
getStats() {
return {
mountNonce: window.__mountNonce,
pathname: window.location.pathname,
lazyLoadCount,
lastRouteParam: window.__lastRouteParam
};
}
};
renderPath(window.location.pathname);
</script>
</body>
</html>
"""
class SpaHandler(BaseHTTPRequestHandler):
def do_GET(self):
body = HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
pass
def main():
server = HTTPServer(("127.0.0.1", 0), SpaHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base_url = f"http://127.0.0.1:{port}"
try:
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
page.goto(f"{base_url}/")
home_h1 = page.text_content("#router-view h1")
card_count = page.locator(".card-link").count()
hash_sample = page.evaluate("window.__routerLab.testHashMode(2)")
# Click BlogCard 1 via RouterLink (SPA navigation without reload)
page.click('.card-link[data-id="1"]')
page.wait_for_selector("article h1")
post1_title = page.text_content("article h1")
post1_h2s = page.eval_on_selector_all("article .content h2", "els => els.map(e => e.textContent)")
stats1 = page.evaluate("window.__routerLab.getStats()")
# Back to home via RouterLink
page.click(".back-link")
page.wait_for_selector(".article-grid")
home_after_back = page.evaluate("window.location.pathname")
# Navigate to missing post /post/999 -> not-found view
page.click("#link-404")
page.wait_for_selector(".not-found")
not_found_h2 = page.text_content(".not-found h2")
not_found_msg = page.text_content(".not-found-msg")
stats404 = page.evaluate("window.__routerLab.getStats()")
# Return home from 404
page.click(".not-found .back-link")
page.wait_for_selector(".article-grid")
final_path = page.evaluate("window.location.pathname")
finally:
browser.close()
finally:
server.shutdown()
server.server_close()
actuals = {
"router_history_and_hash_modes": {
"home_h1": home_h1,
"card_count": card_count,
"history_path": stats1["pathname"],
"hash_sample": hash_sample,
},
"router_link_spa_navigation_no_reload": {
"mount_nonce_preserved": stats1["mountNonce"],
"lazy_loads_after_post1": stats1["lazyLoadCount"],
"home_after_back": home_after_back,
},
"use_route_params_string_and_post_view": {
"param_raw": stats1["lastRouteParam"]["raw"],
"param_type": stats1["lastRouteParam"]["rawType"],
"param_numeric": stats1["lastRouteParam"]["numeric"],
"post1_title": post1_title,
"post1_h2s": post1_h2s,
},
"post_not_found_and_back_home": {
"not_found_path": stats404["pathname"],
"not_found_h2": not_found_h2,
"not_found_msg": not_found_msg,
"final_path": final_path,
},
}
expected = {
"router_history_and_hash_modes": {
"home_h1": "最新文章",
"card_count": 2,
"history_path": "/post/1",
"hash_sample": "#/post/2",
},
"router_link_spa_navigation_no_reload": {
"mount_nonce_preserved": "SPA-NONCE-43",
"lazy_loads_after_post1": 1,
"home_after_back": "/",
},
"use_route_params_string_and_post_view": {
"param_raw": "1",
"param_type": "string",
"param_numeric": 1,
"post1_title": "Vue3 入门完全指南",
"post1_h2s": ["为什么学 Vue3?", "ref 与 reactive"],
},
"post_not_found_and_back_home": {
"not_found_path": "/post/999",
"not_found_h2": "文章不存在",
"not_found_msg": "找不到 ID 为 999 的文章",
"final_path": "/",
},
}
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-vue-router-lab/explore-blog-vue-router.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-vue-router.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a809.zip