豫ICP备2024044691号-1
powered by emlog
vue3 动态添加路由
Mins 2024-10-7 09:19 vue
import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/home/Home.vue'
import useUserUtils from '@/utils/user'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home,
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/login/Login.vue'),
        },
        {
            path: '/:pathMatch(.*)*',
            component: () => import('@/views/notFound/NotFound.vue'),
        }
    ],
})

// 标志来确保路由只加载一次
let routesLoaded = false;

// 迭代器-添加子路由
const addRouteIteration= (list, router) => {
    list.forEach(route => {
        if(route.componentPath){
            route.component = () => import(/* @vite-ignore */route.componentPath)
            router.addRoute(route)
        }

        if(route.children) {
            addRouteIteration(route.children, router)
        }
    })
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
    if (to.path === '/') {
        next()
    } else {
        if (!routesLoaded) {
            const routes = await useUserUtils.getUserRoutes()
            addRouteIteration(routes, router)
            routesLoaded = true
            next({ path: to.path })
        } else {
            next()
        }
    }
})

export default router