路由系统
为 TaskHub 接入 Vue Router,划分 Dashboard 与 Login 视图,实测全局前置守卫 beforeEach 权限拦截、meta 动态标题、动态参数与 404 回退及退出登录历史记录行为。
学完这一章,你能够
- 为 TaskHub 接入 Vue Router,划分 Dashboard 与 Login 视图,实测全局前置守卫 beforeEach 权限拦截、meta 动态标题、动态参数与 404 回退及退出登录历史记录行为。
安装 Vue Router 与基础路由配置
在持久化状态之上,路由系统不仅负责多页面切换,还承担权限控制与动态标题等企业级职责。执行 `npm install vue-router` 后,在 `src/router/index.js` 中用 `createRouter` 与 `createWebHistory()` 定义 `/login`(`Login.vue`,`meta.requiresAuth: false`)与 `/`(`Dashboard.vue`,`meta: { title: '我的工作台', requiresAuth: true, breadcrumb: '首页' }`)两条路由,并通过 `() => import(...)` 实现路由级按需懒加载。
随后创建 `src/views` 目录完成职责拆分:`src/App.vue` 精简为根容器,仅放置 `bg-slate-50 min-h-screen` 外壳、`<router-view v-slot="{ Component }">` 与 `<transition name="page" mode="out-in">` 淡入淡出过渡;原任务界面迁入 `src/views/Dashboard.vue`,新增登录页 `src/views/Login.vue`。
页面拆分、登录页与权限守卫拦截
`Dashboard.vue` 保留任务 Store、四组件与列表动画,并引入 `useRouter()` 新增 `handleLogout`(移除 `localStorage` 中的 `isLoggedIn` 后调用 `router.push('/login')`);`Login.vue` 借助 `isLoading` 状态在点击“一键进入系统”后禁用按钮并显示“登录中...”,异步完成后写入 `isLoggedIn='true'` 并跳转 `/`。
在 `router/index.js` 中注册 `router.beforeEach` 全局前置守卫:读取 `localStorage.getItem('isLoggedIn') === 'true'`,未登录访问需要鉴权的页面时重定向至 `/login`,已登录却访问 `/login` 时导回 `/`,其余情况放行;同时在 `src/main.js` 中依次调用 `app.use(createPinia())` 与 `app.use(router)` 完成挂载。
实测联调效果与核心要点
本站通过支持 SPA 回退的本地 `127.0.0.1` 服务器在 Chromium 中完整实测四条链路:未登录访问 `/` 时守卫记录 `/->/login` 并跳转到 `/login`,`document.title` 切换为“登录 - TaskHub”,外壳继承浅灰背景 `rgb(248, 250, 252)`;点击登录按钮先进入禁用的“登录中...”态,随后进入 `/` 工作台(标题“我的工作台”、面包屑“首页”),此时再访问 `/login` 会被导回 `/`,刷新页面仍保持登录态与 `1` 条持久化任务;此外补充实测动态详情路径 `/task/42` 正确渲染“任务 #42”,未知路径 `/missing-route` 命中 404 回退页。
核心要点有三:第一,`App.vue` 作为 SPA 外壳抽空后,可随 URL 变化在出口中动态切换页面视图;第二,`Dashboard.vue` 退出登录调用 `router.push('/login')` 会新增浏览器历史记录,本站实测点击退出后 `history.length` 增长、`isLoggedIn` 清空,随后触发浏览器后退虽然尝试回退 `/` 但立即被 `beforeEach` 拦截回 `/login`;第三,在 `App.vue` 顶层容器声明 `bg-slate-50` 与 `min-h-screen` 可让所有子视图统一继承基础底色与视口高度。
实测 SPA History 路由守卫、登录态持久化、动态参数路由与退出历史回退拦截
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
router.push 会在浏览器历史栈压入新记录,用户点击后退会重新尝试访问原受保护页面(需靠 beforeEach 再次拦回登录页);router.replace 会替换当前历史记录,不会把退出前的受保护页面留在后退栈顶。