HLJ 发布于
2025-05-22 15:08:51
0阅读

Vue3 Router守卫与属性详解

在 Vue3 的 Vue Router 中,路由守卫和路由实例属性是控制导航行为和访问路由信息的关键部分。以下是详细的说明:


一、导航守卫 (Navigation Guards)

导航守卫用于在路由跳转前后执行特定逻辑(如权限验证、数据预加载等)。

1. 全局守卫

  • router.beforeEach((to, from, next) => { ... })
    用途:全局前置守卫,在路由跳转前触发。
    参数

    • to: 目标路由对象
    • from: 当前路由对象
    • next(): 必须调用此函数继续导航(可传 false 取消、path 重定向等)。
  • router.beforeResolve((to, from, next) => { ... })
    用途:全局解析守卫,在导航被确认前触发(适合处理异步组件或数据预加载)。

  • router.afterEach((to, from) => { ... })
    用途:全局后置守卫,导航完成后触发(无 next 参数,常用于日志记录)。

2. 路由独享守卫

  • beforeEnter
    用途:在单个路由配置中定义,仅在进入该路由前触发。
    const routes = [
      {
        path: '/admin',
        component: Admin,
        beforeEnter: (to, from, next) => { ... }
      }
    ];
    

3. 组件内守卫

  • beforeRouteEnter(to, from, next)
    用途:在组件渲染前调用(无法访问 this,可通过 next(vm => { ... }) 访问组件实例)。

  • beforeRouteUpdate(to, from, next)
    用途:当前路由改变但组件复用时触发(例如 /user/1/user/2,可访问 this)。

  • beforeRouteLeave(to, from, next)
    用途:在离开当前路由前触发(常用于阻止用户未保存离开)。

守卫执行顺序

  1. beforeRouteLeave(组件内)
  2. beforeEach(全局)
  3. beforeEnter(路由独享)
  4. beforeRouteEnter(组件内)
  5. beforeResolve(全局)
  6. afterEach(全局)

二、Router 实例属性和方法

通过 createRouter 创建的实例 (router) 包含以下核心属性和方法:

1. 属性

  • currentRoute
    用途:返回当前激活的路由对象(响应式,等同于 useRoute())。

    console.log(router.currentRoute.value.path);
    
  • options
    用途:获取创建路由时的配置对象。

    console.log(router.options.routes);
    

2. 方法

  • addRoute(parentName?, route)
    用途:动态添加路由规则。

    router.addRoute({ path: '/new', component: NewComponent });
    
  • push(path) / replace(path)
    用途:导航到新路由(push 添加历史记录,replace 替换当前记录)。

    router.push('/home');
    router.replace('/login');
    
  • go(n) / back() / forward()
    用途:控制历史记录跳转。

    router.go(-1); // 后退一步
    router.back();  // 等同于 go(-1)
    
  • hasRoute(name)
    用途:检查是否存在指定名称的路由。

    if (router.hasRoute('admin')) { ... }
    
  • getRoutes()
    用途:获取所有路由记录的完整列表。

    const routes = router.getRoutes();
    
  • resolve(location)
    用途:解析路由位置,返回其详细信息(如 href)。

    const resolved = router.resolve('/user/1');
    console.log(resolved.href);
    
  • isReady()
    用途:返回 Promise,在路由初始化完成后触发。

    router.isReady().then(() => { ... });
    

三、路由对象属性

在导航守卫或 useRoute() 中访问的路由对象 (to/from) 包含以下关键属性:

  • path: 当前路由路径(如 /user/1)。
  • name: 路由名称(需在配置中定义)。
  • params: 动态路径参数(如 /user/:id{ id: '1' })。
  • query: URL 查询参数(如 ?name=John{ name: 'John' })。
  • hash: URL 的 hash 值(如 #section)。
  • fullPath: 完整路径(包含 path + query + hash)。
  • matched: 匹配的路由记录数组(包含嵌套路由信息)。

四、使用场景示例

  • 权限控制:在 beforeEach 中检查用户权限。
  • 数据预加载:在 beforeRouteEnter 中获取数据。
  • 动态路由:通过 addRoute 动态添加管理后台路由。
  • 滚动行为:在 afterEach 中重置页面滚动位置。

总结

Vue Router 的守卫和属性提供了对路由流程的细粒度控制,合理使用可以优化导航逻辑、提升用户体验。在 Vue3 中结合 Composition API(如 useRouter()useRoute()),能更灵活地管理路由交互。

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2025-05-22/682.html
最后生成于 2025-06-05 14:59:56
此内容有帮助 ?
0