对于一个后台系统,需要自定义的页面路由表

routes

这个路由对象定义了每个各个页面的路径,可以在页面下创建子页面。通过将 import() 函数保存在 component 中,可以访问到该路径时候才开始加载。

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginPage.vue'),
  },
  {
    path: '/',
    // requiresAuth 登录保护:需要登录
    meta: { requiresAuth: true },
    component: AppLayout,
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('@/views/HomePage.vue'),
      },
      {
        path: 'problems',
        name: 'problems',
        component: () => import('@/views/ProblemListPage.vue'),
      },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/',
  },
]

router 对象创建

定义了历史记录页面的保存方式,以及上面写好的路由表。

const router = createRouter({
  history: createWebHistory(),
  routes,
})

前置路由守卫

在加载需要登录的页面的时候,需要检查是否有权限,添加 router.beforeEach() 函数可定义在跳转前都执行的函数。一般未登录时候访问,跳转到登录页;已登录还在登录页跳转来源页面或主页。

router.beforeEach((to) => {
  const authStore = useAuthStore()
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    // 定向到登录页,并附加想要登录的页面查询参数
    return { name: 'login', query: { redirect: to.fullPath } }
  }
  if (to.name === 'login' && authStore.isLoggedIn) {
    return { path: '/' }
  }
})