一、安装与配置
-
安装 Vue Router
npm install vue-router@4 # 或 yarn add vue-router@4
-
基本配置
// router/index.js import { createRouter, createWebHistory } from 'vue-router' import Home from '../views/Home.vue' import About from '../views/About.vue' const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ] const router = createRouter({ history: createWebHistory(), routes }) export default router
-
在 main.js 中挂载
import { createApp } from 'vue' import App from './App.vue' import router from './router' const app = createApp(App) app.use(router) app.mount('#app')
二、路由基础组件
-
<router-view>
用于渲染匹配到的路由组件,通常放在布局文件中:<template> <div id="app"> <router-view /> </div> </template>
-
<router-link>
用于导航的组件,替代<a>
标签:<router-link to="/">Home</router-link> <router-link to="/about">About</router-link>
三、路由匹配(无对应路由则跳转至该路由)
{ path: '/:pathMatch(.*)*', component: NotFound }
四、嵌套路由
通过 children
配置子路由:
const routes = [
{
path: '/user',
component: UserLayout,
children: [
{ path: '', component: Profile }, // /user
{ path: 'posts', component: Posts } // /user/posts
]
}
]
五、命名路由与命名视图
-
命名路由
通过name
属性简化路由跳转:{ path: '/settings', name: 'Settings', component: Settings }
<router-link :to="{ name: 'Settings' }">Settings</router-link>
六、编程式导航
通过 router
实例方法控制导航:
import { useRouter } from 'vue-router'
const router = useRouter()
// 跳转到指定路径
router.push('/about')
// 带参数
router.push({ name: 'User', params: { id: 1 } })
// 替换当前历史记录
router.replace('/home')
// 前进/后退
router.go(1) // 前进一步
router.go(-1) // 后退一步
七、路由重定向与别名
-
重定向
{ path: '/old-path', redirect: '/new-path' }
-
别名
{ path: '/home', component: Home, alias: '/welcome' }
八、导航守卫
-
全局前置守卫
router.beforeEach((to, from, next) => { if (to.meta.requiresAuth && !isAuthenticated) { next('/login') } else { next() } })
-
路由独享守卫
{ path: '/admin', component: Admin, beforeEnter: (to, from, next) => { // 权限校验逻辑 } }
-
组件内守卫
<script setup> import { onBeforeRouteLeave } from 'vue-router' onBeforeRouteLeave((to, from, next) => { if (hasUnsavedChanges) { confirm('确定离开?') ? next() : next(false) } else { next() } }) </script>
九、路由懒加载
优化首屏加载速度:
const routes = [
{
path: '/dashboard',
component: () => import('../views/Dashboard.vue')
}
十:Route与Router的区别
1. router
(路由实例)
-
是什么
router
是全局路由器的实例(通过createRouter
创建),负责管理整个应用的路由逻辑。 -
核心职责
-
控制导航(跳转、前进、后退)
-
管理路由配置(
routes
数组) -
注册全局路由守卫
-
-
获取方式
import { useRouter } from 'vue-router' const router = useRouter() // 组合式 API
-
在选项式 API 中通过
this.$router
访问。
-
-
常用方法
router.push('/path') // 跳转到新路由(添加历史记录) router.replace('/path') // 替换当前路由(不添加历史记录) router.go(-1) // 后退一步 router.back() // 等价于 go(-1) router.forward() // 等价于 go(1)
2. route
(当前路由对象)
-
是什么
route
是当前激活的路由信息对象,表示当前 URL 解析后的状态。 -
核心职责
-
提供当前路由的详细信息(路径、参数、查询等)
-
反映当前 URL 的实时状态
-
-
获取方式
import { useRoute } from 'vue-router' const route = useRoute() // 组合式 API
-
在选项式 API 中通过
this.$route
访问。
-
-
关键属性
route.path // 当前路径(如 "/user/1") route.params // 动态参数(如 { id: '1' }) route.query // URL 查询参数(如 ?name=John → { name: 'John' }) route.hash // URL 哈希(如 #section) route.meta // 路由元信息(自定义数据) route.matched // 匹配的路由记录数组(用于嵌套路由)
3. 对比表格
特性 | router | route |
---|---|---|
类型 | 路由管理器(主动控制导航) | 当前路由信息(被动反映状态) |
典型用途 | 跳转路由、全局配置 | 获取参数、查询、路径等信息 |
修改 URL | ✅ 可以(通过 push /replace ) | ❌ 只读 |
响应式 | ❌ 不是响应式对象 | ✅ 是响应式对象(自动更新) |
获取方式 | useRouter() 或 this.$router | useRoute() 或 this.$route |
4. 典型场景示例
场景 1:编程式导航(使用 router
)
import { useRouter } from 'vue-router'
const router = useRouter()
// 跳转到用户详情页(携带参数)
router.push({ name: 'User', params: { id: 123 } })
场景 2:获取动态参数(使用 route
)
<template>
<div>User ID: {
{ route.params.id }}</div>
</template>
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
</script>
十一:路由传参
query参数
-
传递参数
<!-- 跳转并携带query参数(to的字符串写法) --> <router-link to="/news/detail?a=1&b=2&content=欢迎你"> 跳转 </router-link> <!-- 跳转并携带query参数(to的对象写法) --> <RouterLink :to="{ //name:'xiang', //用name也可以跳转 path:'/news/detail', query:{ id:news.id, title:news.title, content:news.content } }" > { {news.title}} </RouterLink>
-
接收参数:
import {useRoute} from 'vue-router' const route = useRoute() // 打印query参数 console.log(route.query)
params参数
-
传递参数
<!-- 跳转并携带params参数(to的字符串写法) --> <RouterLink :to="`/news/detail/001/新闻001/内容001`">{ {news.title}}</RouterLink> <!-- 跳转并携带params参数(to的对象写法) --> <RouterLink :to="{ name:'xiang', //用name跳转 params:{ id:news.id, title:news.title, content:news.title } }" > { {news.title}} </RouterLink>
-
接收参数:
import {useRoute} from 'vue-router' const route = useRoute() // 打印params参数 console.log(route.params)
备注1:传递
params
参数时,若使用to
的对象写法,必须使用name
配置项,不能用path
。备注2:传递
params
参数时,需要提前在规则中占位。
路由的props配置
作用:让路由组件更方便的收到参数(可以将路由参数作为props
传给组件)
{
name:'xiang',
path:'detail/:id/:title/:content',
component:Detail,
// props的对象写法,作用:把对象中的每一组key-value作为props传给Detail组件
// props:{a:1,b:2,c:3},
// props的布尔值写法,作用:把收到了每一组params参数,作为props传给Detail组件
// props:true
// props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件
props(route){
return route.query
}
}