Vue Router【前端】
学无止境
目录
- Vue Router 常用方法对比
- 举例
- router.push / router.replace的参数
- router.push / router.replace 参数形式
- 字符串形式
- 对象形式
- 使用示例
- 通过 name + params(推荐,配合动态路由)
- 通过 path + query
- 带hash
- 带 state(Vue Router 4 新增)
- 总结
Vue Router 常用方法对比
方法 | 功能 | 特点 | 适用场景 |
---|---|---|---|
router.push(location) | 跳转到一个新路由 | 会往 历史栈添加一条记录(类似浏览器点击链接) | 用户正常跳转,需要保留返回历史时 |
router.replace(location) | 跳转到一个新路由 | 替换当前历史记录,不会新增历史 | 登录后跳转首页、表单提交后跳转结果页(不希望用户点返回回到之前页面) |
router.go(n) | 在历史记录中前进/后退 n 步 | 类似浏览器 history.go(n) | 例如:router.go(-1) 返回上一页 |
router.back() | 返回上一个历史记录 | 等同于 router.go(-1) | 返回上页按钮 |
router.forward() | 前进到下一个历史记录 | 等同于 router.go(1) | 不常用,一般浏览器自带前进功能 |
举例
// push - 会新增历史记录
router.push({ name: 'User', params: { id: 123 } })// replace - 替换当前历史
router.replace({ path: '/home' })// go/back/forward
router.go(-1) // 返回上一个页面
router.back() // 同上
router.forward() // 前进一页
router.push / router.replace的参数
router.push / router.replace 参数形式
字符串形式
router.push('/home') // 等同于模板写 <router-link to="/home">
对象形式
router.push({path: '/user/123',query: { page: 1, order: 'desc' }
})
可选属性:
参数 | 类型 | 说明 | 示例 |
---|---|---|---|
path | string | 路径字符串(绝对/相对路径) | /home , user/profile |
name | string | 命名路由的名字(推荐用这个方式) | { name: 'User', params: { id: 123 } } |
params | object | 动态路由参数(只能配合 name 使用,不能和 path 混用) | { name: 'User', params: { id: 123 } } |
query | object | 查询参数,会拼接到 URL 上 | { path: '/home', query: { page: 2 } } → /home?page=2 |
hash | string | 页面锚点(以 # 开头) | { path: '/about', hash: '#team' } → /about#team |
state | object (仅 Vue Router 4,基于 history.state) | 给路由传递额外状态,不显示在 URL 上 | { path: '/home', state: { from: 'login' } } |
使用示例
通过 name + params(推荐,配合动态路由)
// 定义路由
{ path: '/user/:id', name: 'User', component: User }// 跳转
router.push({ name: 'User', params: { id: 123 } })
// → /user/123
注意:params 不能和 path 同时使用,否则会被忽略。
params 必须在路由配置里有占位符(动态路由参数) 才能生效,否则传了也不会显示在 URL 里。
通过 path + query
router.push({ path: '/search', query: { keyword: 'vue', page: 1 } })
// → /search?keyword=vue&page=1
带hash
router.push({ path: '/about', hash: '#contact' })
// → /about#contact
带 state(Vue Router 4 新增)
router.push({ path: '/home', state: { from: 'login' } })// 在目标页获取
console.log(router.options.history.state.from) // 'login'
总结
- path → 明确写死路径。
- name + params → 动态路由(推荐方式)。
- query → 查询参数(URL 上显示)。
- hash → 页面锚点跳转。
- state → Vue Router 4 新增,用于隐藏传参。