Chapter 05: 路由与状态管理
Vue Router
1. 路由配置
1.1 基础路由配置
// router/index.ts
import {
createRouter, createWebHistory } from 'vue-router'
import type {
RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue')
},
{
path: '/users',
name: 'Users',
component: () => import('@/views/Users.vue'),
meta: {
requiresAuth: true,
roles: ['admin']
}
},
{
path: '/users/:id',
name: 'UserDetail',
component: () => import('@/views/UserDetail.vue'),
props: true
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('@/views/NotFound.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
1.2 路由守卫
// 全局前置守卫
router.beforeEach(async (to, from) => {
const authStore = useAuthStore()
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
return {
name: 'Login',
query: {
redirect: to.fullPath }
}
}
if (to.meta.roles && !authStore.hasRole(to.meta.roles)) {
return {
name: 'Forbidden' }
}
})
// 路由独享守卫
{
path: '/profile',
component: UserProfile,
beforeEnter: (to
标签:Chapter,vue,name,05,router,import,path,路由
From: https://blog.csdn.net/qq_36597625/article/details/145076190