后台系统在切换页面时不仅要改变路由,还要验证会话、判断访问权限并保护未保存的编辑内容。Vue Router 4 提供多个导航守卫,可以将这些逻辑放在适当的阶段。本文讨论客户端路由控制,不把它当成服务端权限检查的替代品。
1. 定义路由及元信息契约
使用 meta 表达页面访问要求,而不是在各个组件中分别判断路径字符串。页面名称和访问规则集中定义。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/ff3614ed36c1ebaeabd92a47ed560eed4799e07a">
<nav aria-label="后台导航"><RouterLink :to="{ name: 'dashboard' }">工作台</RouterLink></nav>
</div>
const routes = [
{
path: '/login', name: 'login', component: LoginPage },
{
path: '/dashboard', name: 'dashboard', component: DashboardPage, meta: {
requiresAuth: true } }
];
2. 创建全局前置守卫
beforeEach 适合跨页面通用的会话检查。Vue Router 4 可以通过返回 false 取消导航,或者返回新的路由位置进行重定向。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a2f13ad1991e0f598de03b9a82da17f67f901b33">
<main><RouterView /></main>
</div>
router.beforeEach(async to => {
if (!to.meta.requiresAuth) return true;
await session.ensureInitialized();
return session.authenticated || {
name: 'login', query: {
returnTo: to.fullPath } };
});
3. 合并会话初始化请求
用户可能快速点击多个路由。如果每次守卫都发起独立会话请求,会造成重复网络访问。会话服务可以共享尚未完成的初始化 Promise,并在失败后释放它。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/690f209d77c4b377f85c70fd81fbe6842ab0b57f">
<p v-if="session.initializing" role="status">正在确认登录状态</p>
</div>
let initialization: Promise<void> | undefined;
function ensureInitialized() {
if (session.ready) return Promise.resolve();
return initialization ??= readSession().finally(() => {
initialization = undefined; });
}
4. 区分未登录和权限不足
认证成功不等于可以访问每个模块。角色规则可用于界面导航过滤,但 API 仍必须检查真实权限。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/b3b4fcbc146dd1ed3ab4df1254f6c98582be52b3">
<section role="alert"><h2>没有访问权限</h2><p>请联系系统管理员确认权限。</p></section>
</div>
router.beforeEach(to => {
const permission = to.meta.permission;
if (typeof permission === 'string' && !session.can(permission)) return {
name: 'forbidden' };
});
5. 安全处理登录后的返回路径
登录页接收 returnTo 时不能直接信任任意 URL。只接受本应用允许的站内路径,并通过路由解析和业务白名单验证。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/5de111f3a6f0157e24507ff84a74e361871d8be2">
<form @submit.prevent="signIn"><button type="submit">登录并继续</button></form>
</div>
function resolveReturnTo(input: unknown) {
if (typeof input !== 'string' || !input.startsWith('/') || input.startsWith('//') || input.includes('\\')) return {
name: 'dashboard' };
const resolved = router.resolve(input);
return resolved.matched.length && resolved.name !== 'login' ? resolved.fullPath : {
name: 'dashboard' };
}
6. 阻止离开尚未保存的页面
onBeforeRouteLeave 适合局部编辑页面。应只在确实有未保存更改时弹出确认,并在保存成功后更新基准状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c87f96dedb85b409d95f44c0fadc616b09e44225">
<section><textarea v-model="draft" aria-label="编辑备注" /><p v-if="dirty">尚未保存</p></section>
</div>
import {
onBeforeRouteLeave } from 'vue-router';
onBeforeRouteLeave(async () => {
if (!dirty.value) return true;
return await confirmDiscardChanges();
});
7. 处理同一路由参数变化
从一个详情 ID 切换到另一个 ID 时,Vue Router 可能复用同一组件实例。仅依赖 onMounted 加载数据会展示旧记录。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/bbaf7a0da085ae220cbd34aef183f95ed9a94cf5">
<article><h2>记录详情</h2><p>{
{ record?.title }}</p></article>
</div>
watch(() => route.params.id, (id, _, onCleanup) => {
const controller = new AbortController();
onCleanup(() => controller.abort());
void loadRecord(String(id), controller.signal);
}, {
immediate: true });
8. 识别导航取消与真正错误
router.push 的 Promise 可以返回导航失败对象。正常取消不应被当成服务端错误弹出。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/397f2296144ec139ad909ed6073bc56fc3d4e558">
<button type="button" @click="goToSettings">打开设置</button>
<p v-if="navigationMessage" role="status">{
{ navigationMessage }}</p>
</div>
import {
isNavigationFailure, NavigationFailureType } from 'vue-router';
const failure = await router.push({
name: 'settings' });
if (isNavigationFailure(failure, NavigationFailureType.aborted)) navigationMessage.value = '已取消页面切换';
9. 在导航完成后执行展示更新
afterEach 不能再阻止导航,但可以用于更新页面标题或清理界面提示。接收 failure 参数,避免在失败时误报页面已经切换。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/c4d40e68ab325d4ea2cb67f1d4cf853bcc66f3f6">
<header><h1>{
{ route.meta.title ?? '工作台' }}</h1></header>
</div>
router.afterEach((to, _from, failure) => {
if (!failure && typeof to.meta.title === 'string') document.title = to.meta.title;
});
10. 验证守卫顺序与恢复行为
测试未登录访问、会话失效、权限不足、保存失败后离开及快速切换。用户关闭浏览器或刷新页面不是普通路由导航,需要单独考虑浏览器的离开确认机制。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/01c942d8579e23b288f501b962138fff6b7afa56">
<ul aria-label="导航验收"><li>登录后恢复合法路径</li><li>未保存时可取消导航</li><li>权限不足时展示独立页面</li></ul>
</div>
总结
导航守卫应按照职责分层:全局会话、权限规则和局部编辑保护分别管理。结合明确的导航失败语义、可取消的数据读取以及服务端授权,才能让复杂后台导航保持一致。