Vue Router $route 和$router的区别

文章类型:Vue

发布者:hp

发布时间:2025-04-18

一:定义

(1)$route=>当前路由的状态对象‌,包含 URL 解析后的参数、路径等信息。它是一个‌只读‌的响应式对象‌

(2)$router=>‌Vue Router 的实例对象‌,用于全局路由控制‌

二:作用

(1)$route=>提供当前路由的详细信息

(2)$router=>实现编程式导航和路由配置管理

三:属性

(1)$route

   path‌:当前路由路径(如 /user/123)‌

   ‌params‌:动态路由参数(如 /user/:id 中的 id)‌

   ‌query‌:URL 查询参数(如 ?name=vue)‌

   ‌name‌:路由配置中定义的名称(如果有)‌

‌    meta‌:路由元信息(如权限标识)‌

(2)$router

   push()‌:导航到新路由,并记录到历史栈(如 this.$router.push('/home'))‌

‌    replace()‌:替换当前路由,不保留历史记录‌

   ‌go(n)‌:前进或后退 n 步历史记录(如 go(-1) 表示后退)‌

‌    back()‌ / ‌forward()‌:直接后退或前进‌

四:代码

1:$route=>用于‌获取当前路由信息

// 获取动态参数
const userId = this.$route.params.id;  // ‌:ml-citation{ref="1,3" data="citationList"}
// 获取查询参数
const searchKeyword = this.$route.query.keyword;  // ‌:ml-citation{ref="2,3" data="citationList"}

2:$router‌=>用于‌主动控制路由行为

// 跳转到指定路由(保留历史)
this.$router.push({ name: 'user', params: { id: 123 } });  // ‌:ml-citation{ref="3,6" data="citationList"}
// 替换当前路由(无历史记录)
this.$router.replace('/login');  // ‌:ml-citation{ref="3,6" data="citationList"}

五:总结

1:$route‌:关注‌当前路由状态‌,提供只读的路由信息‌

2:$router‌:关注‌路由操作‌,实现导航和全局路由管理‌