主题
概念卡片:Vue Router 路由机制
一句话机制:Vue Router 用 hash 或 history 两种模式把 URL 与组件视图同步起来,核心是「路由表(path → 组件)+ 路由守卫(访问控制)」;组合式 API 里靠
useRouter()拿「路由器实例」做跳转、靠useRoute()拿「当前路由对象」读参数。
两个最易混的 use 函数
| 函数 | 返回 | 用途 |
|---|---|---|
useRouter() | 路由器实例 | 跳转:push / replace / go |
useRoute() | 当前路由对象 | 读信息:params / query / path |
记忆钩子:Router 带 r 是「跳转用的路由器」,Route 不带 r 是「当前这条路由」。
关键代码示例
动态路由 + 取参(/showDetail/:id 或 ?id=1):
js
import { useRoute } from 'vue-router'
const route = useRoute()
route.params.id // 路径参数 /showDetail/1 → 1
route.query.id // 键值对参数 /showDetail?id=1 → 1
// 模板里也可用 $route.params.id全局守卫(登录控制):
js
router.beforeEach((to, from, next) => {
if (to.path == '/login') return next()
if (localStorage.getItem('username')) return next()
next('/login') // 未登录跳登录,注意避免无限重定向
})
router.afterEach((to, from) => { console.log(`from ${from.path} to ${to.path}`) })路由守卫的类型
| 类型 | 注册方式 |
|---|---|
| 全局前置 | router.beforeEach((to, from, next) => {}) |
| 全局后置 | router.afterEach((to, from) => {}) |
| 路由独享 | 路由配置里 beforeEnter |
不变量(必须成立的约束)
- 动态路由(
/user/:id)参数变化时组件默认复用,不会重新创建——要响应变化须watch(() => route.params.id, ...)。 - 嵌套路由用
children声明,子路由路径不加前导/,用<router-view>渲染。 - 全局前置守卫
next()不调用即拦截;next('/地址')会重定向,但要避免无限重定向。 - 编程式导航用
useRouter().push(),声明式导航用<router-link to="...">。
踩坑案例
- 现象:
/showDetail/1切到/showDetail/2,页面数据不刷新。 原因:同组件复用,setup不重跑。解决:watch(() => route.params.id, ...)重新拉数据。
常见误解
- 把
useRouter和useRoute搞混 → 一个用来跳转、一个用来读参数,搞反报push is not a function。 - 重定向
next('/login')不判断来源 → 登录页也触发守卫形成死循环。
关联
- 总览:Vue3技术栈总览
- 状态:概念卡片:Pinia状态管理
- 源:
B40-资源/语雀-Leo的知识库/框架与vue3/05_Vue3/08_路由机制Router(9 篇)