$route
$route
是根据当前 URL 路径动态生成的,但在嵌套路由场景下各组件的 $route
值可能不同。具体说明如下:
一、核心原理
-
$route
的本质
$route
是 Vue Router 根据当前浏览器 URL 和 路由配置 生成的响应式对象,包含路径、参数、查询等信息。 -
全局唯一性
在同一时刻,整个应用的$route
对象是唯一且共享的。但在嵌套路由场景下,不同组件可能关注$route
的不同部分。
<!-- 页面结构 -->
<template>
<div>
<Header /> <!-- 共享 $route -->
<router-view /> <!-- 渲染当前路由组件,共享 $route -->
<Footer /> <!-- 共享 $route -->
</div>
</template>
2. 嵌套路由组件
在嵌套路由中,虽然 $route
对象是同一个,但不同组件可能关注不同的路由配置。
// 路由配置
const routes = [
{
path: '/user/:id',
component: UserLayout,
children: [
{ path: 'profile', component: UserProfile }, // /user/123/profile
{ path: 'posts', component: UserPosts } // /user/123/posts
]
}
];
此时:
- UserLayout 组件:可以访问完整的
$route
,包括子路由信息 - UserProfile 组件:共享同一个
$route
,但可能只关注$route.path
的profile
部分 - UserPosts 组件:同样共享
$route
,但路径为posts