蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 SPA History 路由守卫、登录态持久化、动态参数路由与退出历史回退拦截

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-taskhub-router.py
explore-taskhub-router.py263 行
"""Offline Playwright Chromium lab for Vue3 Ch36: Vue Router, Auth Guard & Meta."""
import http.server
import json
import socketserver
import threading
from playwright.sync_api import sync_playwright

HTML = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>TaskHub</title>
<style>
  body { margin: 0; font-family: system-ui, sans-serif; }
  #app-shell { min-height: 100vh; background-color: #f8fafc; padding: 20px; box-sizing: border-box; }
  .panel { max-width: 448px; margin: 0 auto; background: #fff; border-radius: 20px; padding: 24px; }
  .page-enter-active, .page-leave-active { transition: opacity 0.2s ease; }
</style>
</head>
<body>
<div id="app-shell">
  <div id="router-view"></div>
</div>
<script>
const routes = [
  { path: '/login', name: 'Login', meta: { title: '登录 - TaskHub', requiresAuth: false } },
  { path: '/', name: 'Dashboard', meta: { title: '我的工作台', requiresAuth: true, breadcrumb: '首页' } },
  { path: '/task/:id', name: 'TaskDetail', meta: { title: '任务详情 - TaskHub', requiresAuth: true, breadcrumb: '任务详情' } }
];

function matchRoute(pathname) {
  for (const r of routes) {
    if (r.path === pathname) return { ...r, params: {}, fullPath: pathname };
    if (r.path === '/task/:id') {
      const m = pathname.match(/^\/task\/([^/]+)$/);
      if (m) return { ...r, params: { id: m[1] }, fullPath: pathname };
    }
  }
  return { path: pathname, name: 'NotFound', params: {}, meta: { title: '404 - 页面不存在', requiresAuth: false }, fullPath: pathname };
}

function getTasks() {
  return JSON.parse(localStorage.getItem('my-tasks') || '[{"id":"1","title":"持久化任务","isCompleted":false}]');
}

function beforeEach(to) {
  const isAuthenticated = localStorage.getItem('isLoggedIn') === 'true';
  if (to.meta.requiresAuth && !isAuthenticated) return '/login';
  if (to.path === '/login' && isAuthenticated) return '/';
  return null;
}

let currentRoute = null;
const guardLog = [];

function renderView(route) {
  document.title = route.meta.title || 'TaskHub';
  const host = document.getElementById('router-view');
  if (route.name === 'Login') {
    host.innerHTML = `
      <div class="panel" data-view="Login">
        <h2>欢迎回来</h2>
        <button id="login-btn" type="button">一键进入系统</button>
        <p>测试环境:点击即可登录</p>
      </div>`;
    const btn = document.getElementById('login-btn');
    btn.addEventListener('click', () => {
      btn.disabled = true;
      btn.textContent = '登录中...';
      setTimeout(() => {
        localStorage.setItem('isLoggedIn', 'true');
        push('/');
      }, 60);
    });
  } else if (route.name === 'Dashboard') {
    const tasks = getTasks();
    host.innerHTML = `
      <div class="panel" data-view="Dashboard">
        <nav id="breadcrumb">${route.meta.breadcrumb}</nav>
        <h1>TaskHub</h1>
        <ul id="dash-tasks">${tasks.map(t => `<li>${t.title}</li>`).join('')}</ul>
        <button id="logout-btn" type="button">退出当前账号</button>
      </div>`;
    document.getElementById('logout-btn').addEventListener('click', () => {
      localStorage.removeItem('isLoggedIn');
      push('/login');
    });
  } else if (route.name === 'TaskDetail') {
    host.innerHTML = `<div class="panel" data-view="TaskDetail"><h2>任务 #${route.params.id}</h2></div>`;
  } else {
    host.innerHTML = `<div class="panel" data-view="NotFound"><h2>404 Not Found: ${route.fullPath}</h2></div>`;
  }
}

function navigate(path, pushState = true) {
  let target = matchRoute(path);
  const redirect = beforeEach(target);
  if (redirect) {
    guardLog.push(`${path}->${redirect}`);
    target = matchRoute(redirect);
    path = redirect;
  }
  currentRoute = target;
  if (pushState && location.pathname !== path) {
    history.pushState({ path }, '', path);
  } else if (!pushState && location.pathname !== path) {
    history.replaceState({ path }, '', path);
  }
  renderView(target);
}

function push(path) { navigate(path, true); }
window.__router = { push, getRoute: () => currentRoute, getGuardLog: () => guardLog };

window.addEventListener('popstate', () => {
  navigate(location.pathname, false);
});

// Initial bootstrap
localStorage.setItem('my-tasks', JSON.stringify(getTasks()));
navigate(location.pathname, false);
</script>
</body>
</html>
"""


class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        # SPA history fallback: serve index HTML for every path
        data = 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(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    srv = socketserver.TCPServer(("127.0.0.1", 0), Handler)
    port = srv.server_address[1]
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            page = browser.new_page()
            base = f"http://127.0.0.1:{port}"

            # Case 1: Unauthenticated access to '/' redirects to '/login' + meta.title + bg-slate-50 inheritance
            page.goto(f"{base}/", wait_until="domcontentloaded")
            act1 = page.evaluate("""() => ({
                pathname: location.pathname,
                title: document.title,
                view: document.querySelector('#router-view > div')?.dataset.view,
                heading: document.querySelector('#router-view h2')?.textContent,
                shellBg: getComputedStyle(document.getElementById('app-shell')).backgroundColor,
                guardLog: window.__router.getGuardLog()
            })""")
            exp1 = {
                "pathname": "/login",
                "title": "登录 - TaskHub",
                "view": "Login",
                "heading": "欢迎回来",
                "shellBg": "rgb(248, 250, 252)",
                "guardLog": ["/->/login"],
            }
            cases.append({"name": "auth_guard_redirect_and_title", "expected": exp1, "actual": act1, "passed": act1 == exp1})

            # Case 2: Login flow, loading state, logged-in '/login' redirect back to '/', reload persistence
            page.click("#login-btn")
            loading_label = page.locator("#login-btn").text_content()
            loading_disabled = page.locator("#login-btn").is_disabled()
            page.wait_for_selector('[data-view="Dashboard"]')
            # Try going to /login while logged in
            page.evaluate("window.__router.push('/login')")
            after_login_guard_path = page.evaluate("location.pathname")
            page.reload(wait_until="domcontentloaded")
            act2 = {
                "loading_label": loading_label,
                "loading_disabled": loading_disabled,
                "after_login_guard_path": after_login_guard_path,
                "reloaded_path": page.evaluate("location.pathname"),
                "reloaded_title": page.title(),
                "breadcrumb": page.locator("#breadcrumb").text_content(),
                "task_count": page.locator("#dash-tasks li").count(),
            }
            exp2 = {
                "loading_label": "登录中...",
                "loading_disabled": True,
                "after_login_guard_path": "/",
                "reloaded_path": "/",
                "reloaded_title": "我的工作台",
                "breadcrumb": "首页",
                "task_count": 1,
            }
            cases.append({"name": "login_flow_and_logged_in_guard", "expected": exp2, "actual": act2, "passed": act2 == exp2})

            # Case 3: Dynamic param route /task/:id and 404 fallback
            page.evaluate("window.__router.push('/task/42')")
            detail_path = page.evaluate("location.pathname")
            detail_text = page.locator("#router-view h2").text_content()
            page.evaluate("window.__router.push('/missing-route')")
            notfound_view = page.locator("#router-view > div").get_attribute("data-view")
            notfound_title = page.title()
            page.evaluate("window.__router.push('/')")
            act3 = {
                "detail_path": detail_path,
                "detail_text": detail_text,
                "notfound_view": notfound_view,
                "notfound_title": notfound_title,
            }
            exp3 = {
                "detail_path": "/task/42",
                "detail_text": "任务 #42",
                "notfound_view": "NotFound",
                "notfound_title": "404 - 页面不存在",
            }
            cases.append({"name": "dynamic_param_and_404_fallback", "expected": exp3, "actual": act3, "passed": act3 == exp3})

            # Case 4: Logout via router.push('/login') + browser back intercepted by beforeEach
            hist_before = page.evaluate("history.length")
            page.click("#logout-btn")
            hist_after = page.evaluate("history.length")
            logged_flag = page.evaluate("localStorage.getItem('isLoggedIn')")
            page.go_back()
            page.wait_for_timeout(50)
            act4 = {
                "history_grew": hist_after > hist_before,
                "logged_flag_after_logout": logged_flag,
                "path_after_back": page.evaluate("location.pathname"),
                "view_after_back": page.locator("#router-view > div").get_attribute("data-view"),
            }
            exp4 = {
                "history_grew": True,
                "logged_flag_after_logout": None,
                "path_after_back": "/login",
                "view_after_back": "Login",
            }
            cases.append({"name": "logout_push_history_and_guard", "expected": exp4, "actual": act4, "passed": act4 == exp4})

            browser.close()
    finally:
        srv.shutdown()
        srv.server_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-taskhub-router-lab/explore-taskhub-router.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-taskhub-router.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Vue3

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip

下载课程关联工程包:Vue3

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a836.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习