router.push()
下面,我们来系统的梳理关于 Vue Router router.push()
的基本知识点:
一、router.push()
核心概念
1.1 什么是 router.push()
?
router.push()
是 Vue Router 提供的编程式导航方法,用于在 JavaScript 中以编程方式导航到新的 URL,同时向浏览器的历史记录栈添加一条新记录。
1.2 与声明式导航的对比
特性 | <router-link> (声明式) | router.push() (编程式) |
---|---|---|
使用场景 | 模板中直接使用 | JavaScript 代码中使用 |
灵活性 | 基本导航需求 | 复杂导航逻辑 |
事件处理 | 通过点击触发 | 可在任何事件或条件中触发 |
历史记录 | 添加新记录 | 添加新记录 |
参数传递 | 支持 | 支持更复杂的参数组合 |
1.3 核心作用
- 导航到新路由:改变当前 URL 并渲染对应组件
- 添加历史记录:用户可通过浏览器后退按钮返回
- 传递参数:支持路径参数、查询参数和哈希
- 条件导航:在导航前执行验证逻辑
二、基本使用方法
2.1 字符串路径
// 导航到绝对路径
router.push('/home')// 导航到相对路径
router.push('about') // 基于当前路径// 带查询参数
router.push('/search?query=vue')
2.2 对象形式(推荐)
// 使用路径
router.push({ path: '/user/123' })// 使用命名路由
router.push({ name: 'userProfile', params: { id: 123 } })// 带查询参数
router.push({path: '/register',query: { plan: 'premium' }
})// 带哈希值
router.push({ path: '/about', hash: '#team' })
2.3 带参数的命名路由
// 定义路由
{path: '/user/:id',name: 'user',component: User
}// 导航方式
router.push({ name: 'user', params: { id: 123 } })// 错误:提供 path 时 params 会被忽略
router.push({ path: '/user', params: { id: 123 } }) // -> /user
三、参数传递详解
3.1 路径参数 (params)
// 路由配置
{ path: '/user/:id', name: 'user', component: User }// 导航
router.push({ name: 'user', params: { id: 123 } }) // -> /user/123// 在组件中访问
this.$route.params.id // 123
3.2 查询参数 (query)
// 导航
router.push({path: '/search',query: { q: 'vue', page: 2 }
}) // -> /search?q=vue&page=2// 在组件中访问
this.$route.query.q // 'vue'
this.$route.query.page // '2'
3.3 哈希 (hash)
router.push({path: '/documentation',hash: '#installation'
}) // -> /documentation#installation// 在组件中访问
this.$route.hash // '#installation'
3.4 参数组合使用
router.push({name: 'productDetail',params: