在 Vue3 的 Vue Router 中,路由守卫和路由实例属性是控制导航行为和访问路由信息的关键部分。以下是详细的说明:
导航守卫用于在路由跳转前后执行特定逻辑(如权限验证、数据预加载等)。
router.beforeEach((to, from, next) => { ... })
用途:全局前置守卫,在路由跳转前触发。
参数:
to
: 目标路由对象 from
: 当前路由对象 next()
: 必须调用此函数继续导航(可传 false
取消、path
重定向等)。router.beforeResolve((to, from, next) => { ... })
用途:全局解析守卫,在导航被确认前触发(适合处理异步组件或数据预加载)。
router.afterEach((to, from) => { ... })
用途:全局后置守卫,导航完成后触发(无 next
参数,常用于日志记录)。
beforeEnter
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => { ... }
}
];
beforeRouteEnter(to, from, next)
用途:在组件渲染前调用(无法访问 this
,可通过 next(vm => { ... })
访问组件实例)。
beforeRouteUpdate(to, from, next)
用途:当前路由改变但组件复用时触发(例如 /user/1
→ /user/2
,可访问 this
)。
beforeRouteLeave(to, from, next)
用途:在离开当前路由前触发(常用于阻止用户未保存离开)。
beforeRouteLeave
(组件内) beforeEach
(全局) beforeEnter
(路由独享) beforeRouteEnter
(组件内) beforeResolve
(全局) afterEach
(全局)通过 createRouter
创建的实例 (router
) 包含以下核心属性和方法:
currentRoute
用途:返回当前激活的路由对象(响应式,等同于 useRoute()
)。
console.log(router.currentRoute.value.path);
options
用途:获取创建路由时的配置对象。
console.log(router.options.routes);
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()
),能更灵活地管理路由交互。