import { createRouter, createWebHashHistory, RouteRecordRaw, RouteLocationNormalized } from 'vue-router' import { useStorage, useStorageType } from '@/utils' import { TOKEN, ROUTE_WHITE_LIST, LOGIN_PATH } from '@/constants' // import { useUserStore } from '@/store/user' import NProgress from '@/plugins/NProgress' // 引入顶部进度条插件 const routes: RouteRecordRaw[] = [ { name: 'Login', path: LOGIN_PATH, component: () => import(/* webpackChunkName: "login" */ '@/views/login/index.vue') }, { name: 'Layout', path: '/', redirect: '/main', component: () => import(/* webpackChunkName: "layout" */ '@/layout/index.vue'), children: [ { name: 'Main', path: '/main', meta: { title: '首页', icon: 'location' }, component: () => import('@/views/main/index.vue') } ] }, { name: '404', path: '/404', meta: { title: '页面未找到' }, component: () => import(/* webpackChunkName: "404" */ '@/views/error/404.vue') }, { path: '/:pathMatch(.*)*', redirect: '/404' // 路径不对跳转该页面 } ] const router = createRouter({ history: createWebHashHistory(), routes, /** * 滚动行为 * @param to: 即将要进入的目标 用一种标准化的方式 * @param from: 当前导航正要离开的路由 用一种标准化的方式 * @param savedPosition: popstate 导航时才可用(由浏览器的后退/前进按钮触发) */ scrollBehavior(to, from, savedPosition) { if (savedPosition) { // 返回 savedPosition,在按下 后退/前进 按钮时,就会像浏览器的原生表现那样 return savedPosition } else { return { // 当切换到新路由时,页面滚到顶部 top: 0, // el: to.hash, // 锚点 behavior: 'smooth' // 滚动平滑(动画) } } } }) /** * 全局前置守卫 * @param to: 即将要进入的目标 用一种标准化的方式 * @param from: 当前导航正要离开的路由 用一种标准化的方式 * @param next: 路由放行与跳转 * 场景:登录校验等 */ router.beforeEach(async (to: RouteLocationNormalized) => { // 开启进度条 NProgress.start() const token = useStorage.getItem(TOKEN, useStorageType.Cookies) /* 1.用户未登录操作 */ if (!token) { // 1.1 避免无限重定向 if (!ROUTE_WHITE_LIST.includes(to.path)) return LOGIN_PATH } else { /* 2.用户已登录操作 */ /* const userStore = useUserStore() // 2.1 是否有用户信息 if (!userStore.userInfo) { console.log('没有用户信息,重新获取') await userStore.getUserInfoAction() } */ // 2.2 动态添加加载路由 // 2.3 如果不在白名单就 if (!ROUTE_WHITE_LIST.includes(to.path)) return // 2.4 如果是登录页就跳转当前页或首页 if (to.path === LOGIN_PATH) return '/' } }) /** * 全局后置守卫 * @param to: 即将要进入的目标 用一种标准化的方式 * @param from: 当前导航正要离开的路由 用一种标准化的方式 * @param failure: 检测导航故障 * 场景:分析、更改页面标题、声明页面等辅助功能 */ router.afterEach((to, from, failure) => { if (failure) return false // 关闭进度条 NProgress.done() // 设置网页标题 // document.title = (to.meta.title) as string }) export default router