Vue Router 编程式导航完全指南
vue-router 🚦 The official router for Vue 2 项目地址: https://gitcode.com/gh_mirrors/vu/vue-router
什么是编程式导航
在 Vue Router 中,除了使用 <router-link>
创建声明式导航外,还可以通过路由实例方法实现编程式导航。这种方式为开发者提供了更灵活的控制能力,特别适合在需要根据业务逻辑动态决定导航路径的场景中使用。
核心导航方法
router.push() - 添加新路由记录
router.push()
是最常用的导航方法,它会向浏览器的历史记录栈中添加一个新条目。这意味着用户可以通过浏览器的后退按钮返回到之前的页面。
基本语法:
router.push(location, onComplete?, onAbort?)
使用方式:
// 字符串路径
this.$router.push('/home')
// 对象形式
this.$router.push({ path: '/home' })
// 命名路由带参数
this.$router.push({
name: 'user',
params: { userId: '123' }
})
// 带查询参数
this.$router.push({
path: '/register',
query: { plan: 'vip' }
})
回调函数(2.2.0+版本支持):
onComplete
: 导航成功完成时调用onAbort
: 导航中止时调用
router.replace() - 替换当前路由
与 push()
方法类似,但不会向历史记录添加新条目,而是直接替换当前记录。
// 声明式
<router-link :to="..." replace></router-link>
// 编程式
this.$router.replace('/new-path')
router.go() - 在历史记录中前进/后退
基于当前页面在历史记录栈中的位置进行前进或后退操作。
// 前进1页
this.$router.go(1)
// 后退1页
this.$router.go(-1)
// 前进3页
this.$router.go(3)
实际应用场景
- 表单提交后跳转:
submitForm() {
api.submit().then(() => {
this.$router.push('/success')
})
}
- 权限控制跳转:
checkAuth() {
if (!isAuthenticated) {
this.$router.replace('/login')
}
}
- 多步骤向导:
nextStep() {
this.$router.push({
name: 'wizard',
params: { step: this.currentStep + 1 }
})
}
注意事项
-
参数传递:
- 使用
params
时需配合命名路由 - 使用
query
会显示在URL中
- 使用
-
导航守卫: 编程式导航也会触发全局和路由独享的导航守卫
-
性能考虑: 频繁调用导航方法可能会导致性能问题,应考虑防抖处理
与浏览器History API的关系
Vue Router 的导航方法实际上是对浏览器 History API 的封装:
push()
对应history.pushState()
replace()
对应history.replaceState()
go()
对应history.go()
这种设计使得 Vue Router 在不同路由模式(history、hash、abstract)下都能保持一致的API行为。
总结
编程式导航为 Vue 应用提供了强大的路由控制能力,开发者可以根据业务需求灵活选择使用声明式或编程式导航。理解这些方法的差异和使用场景,能够帮助开发者构建更加强大和用户友好的单页应用。
vue-router 🚦 The official router for Vue 2 项目地址: https://gitcode.com/gh_mirrors/vu/vue-router
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考