refactor: dynamic routes

This commit is contained in:
张传龙 2022-09-18 15:10:22 +08:00
parent 30211e14ea
commit bdbe9b8483
5 changed files with 50 additions and 38 deletions

View File

@ -8,12 +8,12 @@ import { setupRouter } from '@/router'
import { setupStore } from '@/store' import { setupStore } from '@/store'
import App from './App.vue' import App from './App.vue'
function setupApp() { async function setupApp() {
const app = createApp(App) const app = createApp(App)
setupStore(app) setupStore(app)
setupRouter(app) await setupRouter(app)
app.mount('#app') app.mount('#app')
} }

View File

@ -1,13 +1,8 @@
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { NOT_FOUND_ROUTE } from '@/router/routes'
import { getToken, refreshAccessToken } from '@/utils/token' import { getToken, refreshAccessToken } from '@/utils/token'
import { isNullOrWhitespace } from '@/utils/is' import { isNullOrWhitespace } from '@/utils/is'
const WHITE_LIST = ['/login', '/404'] const WHITE_LIST = ['/login', '/404']
export function createPermissionGuard(router) { export function createPermissionGuard(router) {
const userStore = useUserStore()
const permissionStore = usePermissionStore()
router.beforeEach(async (to) => { router.beforeEach(async (to) => {
const token = getToken() const token = getToken()
@ -18,25 +13,9 @@ export function createPermissionGuard(router) {
} }
/** 有token的情况 */ /** 有token的情况 */
if (to.path === '/login') return { path: '/', replace: true } if (to.path === '/login') return { path: '/' }
if (to.path === '/404') return true
// 已经拿到用户信息 refreshAccessToken()
if (userStore.userId) { return true
refreshAccessToken()
return true
}
try {
await userStore.getUserInfo()
const accessRoutes = permissionStore.generateRoutes(userStore.role)
accessRoutes.forEach((route) => {
!router.hasRoute(route.name) && router.addRoute(route)
})
router.addRoute(NOT_FOUND_ROUTE)
return { ...to, replace: true }
} catch (error) {
console.error(error)
return
}
}) })
} }

View File

@ -1,28 +1,53 @@
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router' import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import { setupRouterGuard } from './guard' import { setupRouterGuard } from './guard'
import { basicRoutes } from './routes' import { basicRoutes as routes, EMPTY_ROUTE, NOT_FOUND_ROUTE } from './routes'
import { getToken } from '@/utils/token'
import { isNullOrWhitespace } from '@/utils/is'
import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
const isHash = import.meta.env.VITE_USE_HASH === 'true' const isHash = import.meta.env.VITE_USE_HASH === 'true'
export const router = createRouter({ export const router = createRouter({
history: isHash ? createWebHashHistory('/') : createWebHistory('/'), history: isHash ? createWebHashHistory('/') : createWebHistory('/'),
routes: [], routes,
scrollBehavior: () => ({ left: 0, top: 0 }), scrollBehavior: () => ({ left: 0, top: 0 }),
}) })
export function resetRouter() { export async function resetRouter() {
router.getRoutes().forEach((route) => { router.getRoutes().forEach((route) => {
const { name } = route const { name } = route
router.hasRoute(name) && router.removeRoute(name) router.hasRoute(name) && router.removeRoute(name)
}) })
basicRoutes.forEach((route) => { await addDynamicRoutes()
!router.hasRoute(route.name) && router.addRoute(route)
})
} }
export function setupRouter(app) { export async function addDynamicRoutes() {
basicRoutes.forEach((route) => { const token = getToken()
!router.hasRoute(route.name) && router.addRoute(route)
}) // 没有token情况
app.use(router) if (isNullOrWhitespace(token)) {
setupRouterGuard(router) router.addRoute(EMPTY_ROUTE)
return
}
// 有token的情况
try {
const userStore = useUserStore()
const permissionStore = usePermissionStore()
!userStore.userId && (await userStore.getUserInfo())
const accessRoutes = permissionStore.generateRoutes(userStore.role)
accessRoutes.forEach((route) => {
!router.hasRoute(route.name) && router.addRoute(route)
})
router.hasRoute(EMPTY_ROUTE.name) && router.removeRoute(EMPTY_ROUTE.name)
router.addRoute(NOT_FOUND_ROUTE)
} catch (error) {
console.error(error)
}
}
export async function setupRouter(app) {
await addDynamicRoutes()
setupRouterGuard(router)
app.use(router)
} }

View File

@ -63,6 +63,12 @@ export const NOT_FOUND_ROUTE = {
isHidden: true, isHidden: true,
} }
export const EMPTY_ROUTE = {
name: 'Empty',
path: '/:pathMatch(.*)*',
component: null,
}
const modules = import.meta.glob('@/views/**/route.js', { eager: true }) const modules = import.meta.glob('@/views/**/route.js', { eager: true })
const asyncRoutes = [] const asyncRoutes = []
Object.keys(modules).forEach((key) => { Object.keys(modules).forEach((key) => {

View File

@ -51,6 +51,7 @@ import { setToken } from '@/utils/token'
import { useStorage } from '@vueuse/core' import { useStorage } from '@vueuse/core'
import bgImg from '@/assets/images/login_bg.webp' import bgImg from '@/assets/images/login_bg.webp'
import api from './api' import api from './api'
import { addDynamicRoutes } from '@/router'
const title = import.meta.env.VITE_TITLE const title = import.meta.env.VITE_TITLE
@ -91,6 +92,7 @@ async function handleLogin() {
} else { } else {
lStorage.remove('loginInfo') lStorage.remove('loginInfo')
} }
await addDynamicRoutes()
if (query.redirect) { if (query.redirect) {
const path = query.redirect const path = query.redirect
Reflect.deleteProperty(query, 'redirect') Reflect.deleteProperty(query, 'redirect')