在 Vue Router 中,route
和 router
是两个非常重要的对象,但它们的作用和用途完全不同。以下是它们的区别:
1. route
- 定义:
route
是一个表示当前路由信息的对象,包含了当前激活路由的状态信息。 - 获取方式:在组件中通过
this.$route
访问。 - 作用:用于获取当前路由的详细信息,比如路径、参数、查询字符串等。
- 常用属性:
path
:当前路由的路径(如/user/123
)。params
:动态路由参数(如{ id: '123' }
)。query
:查询参数(如{ name: 'John' }
)。hash
:URL 中的 hash 值(如#section
)。fullPath
:完整的 URL 路径(如/user/123?name=John#section
)。matched
:当前路由匹配的所有路由记录(数组形式)。name
:当前路由的名称(如果定义了路由名称)。
- 示例:// 获取当前路由的动态参数const userId = this.$route.params.id;// 获取查询参数const userName = this.$route.query.name;
// 获取当前路由的动态参数 const userId = this.$route.params.id; // 获取查询参数 const userName = this.$route.query.name;
// 获取当前路由的动态参数 const userId = this.$route.params.id; // 获取查询参数 const userName = this.$route.query.name;
2. router
- 定义:
router
是 Vue Router 的实例,用于控制路由的跳转、导航守卫等操作。 - 获取方式:在组件中通过
this.$router
访问。 - 作用:用于编程式导航、路由跳转、导航守卫等。
- 常用方法:
push
:跳转到指定路由(会向 history 栈中添加一条记录)。replace
:跳转到指定路由(不会向 history 栈中添加记录,替换当前记录)。go
:在 history 记录中前进或后退。back
:后退一步。forward
:前进一步。beforeEach
、beforeResolve
、afterEach
:全局导航守卫。
3. 区别总结
特性 | route | router |
---|---|---|
作用 | 表示当前路由的状态信息 | 控制路由的跳转和导航行为 |
获取方式 | this.$route | this.$router |
常用属性/方法 | path 、params 、query 、hash 等 | push 、replace 、go 、back 等 |
使用场景 | 获取当前路由的详细信息 | 编程式导航、路由跳转、导航守卫 |
4. 示例对比
// 获取当前路由的动态参数(使用 route)const userId = this.$route.params.id;// 跳转到新路由(使用 router)this.$router.push({ path: `/user/${userId}`, query: { name: 'John' } });// 获取当前路由的动态参数(使用 route) const userId = this.$route.params.id; // 跳转到新路由(使用 router) this.$router.push({ path: `/user/${userId}`, query: { name: 'John' } });// 获取当前路由的动态参数(使用 route) const userId = this.$route.params.id; // 跳转到新路由(使用 router) this.$router.push({ path: `/user/${userId}`, query: { name: 'John' } });
5. 总结
route
:用于获取当前路由的状态信息,是只读的。router
:用于控制路由的跳转和导航行为,是可操作的。- 两者通常配合使用,
route
用于获取信息,router
用于执行操作。
THE END
暂无评论内容