在 Vue 3 项目中使用 vue-router 可以实现页面之间的路由跳转和管理。以下是详细的使用步骤和示例:
1. 安装 vue-router
首先需要安装 vue-router 4.x 版本(适用于 Vue 3):
npm install vue-router@4
# 或
yarn add vue-router@4
2. 创建路由配置
在项目中创建路由配置文件,通常放在 src/router 目录下:
import { createRouter, createWebHistory } from 'vue-router'
// 导入组件
import Login from '@/views/Login.vue'
import Home from '@/views/Home.vue'
import Dashboard from '@/views/Dashboard.vue'
import UserList from '@/views/users/List.vue'
import UserDetail from '@/views/users/Detail.vue'
import NotFound from '@/views/NotFound.vue'
// 路由规则
const routes = [
{
path: '/login',
name: 'Login',
component: Login,
meta: {
// 不需要登录权限
requiresAuth: false
}
},
{
path: '/',
name: 'Home',
component: Home,
meta: {
// 需要登录权限
requiresAuth: true
},
// 嵌套路由
children: [
{
path: '', // 默认子路由
name: 'Dashboard',
component: Dashboard
},
{
path: 'users',
name: 'UserList',
component: UserList
},
{
path: 'users/:id', // 动态路由参数
name: 'UserDetail',
component: UserDetail,
props: true // 将路由参数转为组件props
}
]
},
{
path: '/404',
name: 'NotFound',
component: NotFound
},
{
path: '/:pathMatch(.*)*', // 匹配所有未定义的路由
redirect: '/404'
}
]
// 创建路由实例
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), // HTML5 history模式
routes,
// 滚动行为:切换路由时滚动到顶部
scrollBehavior() {
return { top: 0 }
}
})
// 路由守卫:验证登录状态
router.beforeEach((to, from, next) => {
// 检查路由是否需要登录权限
if (to.meta.requiresAuth) {
// 检查本地存储中是否有token
const token = localStorage.getItem('token')
if (token) {
next() // 已登录,继续访问
} else {
// 未登录,跳转到登录页,并记录当前路径以便登录后返回
next({ name: 'Login', query: { redirect: to.fullPath } })
}
} else {
next() // 不需要登录,直接访问
}
})
export default router
3. 在 main.js 中引入路由
需要将路由实例挂载到 Vue 应用中:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router' // 引入路由配置
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
const app = createApp(App)
app.use(router) // 使用路由
app.use(ElementPlus)
app.mount('#app')
4. 在组件中使用路由
模板中使用:
<template>
<!-- 导航链接 -->
<router-link to="/">首页</router-link>
<router-link :to="{ name: 'UserList' }">用户列表</router-link>
<router-link :to="{ name: 'UserDetail', params: { id: 1 } }">用户详情</router-link>
<!-- 路由出口:匹配的组件将在这里渲染 -->
<router-view />
</template>
脚本中使用(Composition API):
<script setup>
import { useRouter, useRoute } from 'vue-router'
// 获取路由实例
const router = useRouter()
// 获取当前路由信息
const route = useRoute()
// 编程式导航
const goToUserDetail = (userId) => {
// 方式1:使用路径
router.push(`/users/${userId}`)
// 方式2:使用命名路由(推荐)
router.push({
name: 'UserDetail',
params: { id: userId }
})
// 带查询参数
router.push({
name: 'UserList',
query: { page: 1, size: 10 }
})
}
// 获取路由参数
console.log(route.params.id) // 动态参数
console.log(route.query.page) // 查询参数
</script>
5. 路由守卫的应用
在前面的路由配置中,我们已经实现了一个全局前置守卫用于验证登录状态。除此之外,还有其他类型的守卫:
- 组件内守卫:
<script setup>
import { onBeforeRouteEnter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
// 进入路由前
onBeforeRouteEnter((to, from, next) => {
// 不能访问组件实例 `this`
next(vm => {
// 通过 `vm` 访问组件实例
})
})
// 离开路由前
onBeforeRouteLeave((to, from, next) => {
const confirmLeave = window.confirm('确定要离开吗?未保存的数据可能会丢失')
if (confirmLeave) {
next()
} else {
next(false) // 取消导航
}
})
// 路由参数变化时(如从 /users/1 到 /users/2)
onBeforeRouteUpdate((to, from, next) => {
// 可以访问组件实例 `this`
next()
})
</script>
- 动态导入组件(路由懒加载)
为了优化性能,可以使用动态导入的方式加载组件:
// 替换静态导入
const UserList = () => import('@/views/users/List.vue')
// 路由配置中直接使用
const routes = [
{
path: 'users',
name: 'UserList',
component: () => import('@/views/users/List.vue') // 直接在这里动态导入
}
]
核心概念总结
- 路由模式:
createWebHistory(HTML5 history 模式,无 #)和createWebHashHistory(hash 模式,带 #) - 路由匹配:通过
path匹配,支持动态参数(:id)和通配符 - 嵌套路由:使用
children配置,对应组件中的<router-view> - 编程式导航:使用
router.push()、router.replace()、router.go()等方法 - 路由守卫:控制路由访问权限,处理导航前后的逻辑
- 路由元信息:通过
meta字段存储路由相关的附加信息
使用 vue-router 可以帮助你构建单页应用(SPA),实现无刷新的页面切换,提升用户体验。结合前面实现的登录功能,可以通过路由守卫控制不同页面的访问权限。

2273

被折叠的 条评论
为什么被折叠?



