Vue Router 4 实战:导航守卫、权限路由与离开页面确认

简介: 本文详解 Vue Router 4 导航守卫在后台系统中的实战应用:涵盖路由元信息契约、全局/局部守卫、会话复用、权限分级、安全重定向、未保存提示、参数变更处理及导航失败识别,强调客户端守卫不替代服务端鉴权。(239字)

后台系统在切换页面时不仅要改变路由,还要验证会话、判断访问权限并保护未保存的编辑内容。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>

总结

导航守卫应按照职责分层:全局会话、权限规则和局部编辑保护分别管理。结合明确的导航失败语义、可取消的数据读取以及服务端授权,才能让复杂后台导航保持一致。

相关文章
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8072 2
|
11天前
|
域名解析 人工智能 Linux
|
21天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18756 64
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10141 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1524 5
|
9天前
|
云安全 数据采集 人工智能
|
16天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2680 8
|
9天前
|
Web App开发 缓存 安全
巨魔商店 TrollStore 安装教程(2026):免电脑在线安装与全机型安装器矩阵_iOS巨魔安装
巨魔商店(TrollStore)是iOS 14–17.0(特定版本)的永久签名工具,无需越狱,利用CoreTrust漏洞实现IPA签名长期有效,彻底告别7天重签。支持免电脑在线安装(TrollHelperOTA),适配多机型/系统组合,开源免费,安全可控。(239字)
2261 0