Vue3+JS 动态路由

86 阅读1分钟
//根据后端返回的角色
import {createRouter, createWebHashHistory} from "vue-router"
import {createNewRouter, roleMenu, index} from "@/assets/js/menuList"
import {ref} from "vue";

const routes = [
    // {path: '/', redirect: '/index'},
    {
        path: '/init',
        name: "init",
        component: () => import('@/views/init.vue')
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login.vue')
    },
    {
        path: '/index',
        name: 'index',
        component: () => import('@/views/index.vue'),
        redirect: '/',
        children: []
    },

    {
        path: '/:catchAll(.*)*',
        component: () => import('@/views/404.vue'),
        hidden: true
    }
]
const isManage = ref(true)
const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})
let done = true
router.beforeEach((to, from, next) => {
    let index2 = sessionStorage.getItem('manageType')
    if (to.path === '/init' || to.path === '/login') {
        next()
        return;
    }
    if (done && index2) {
        done = false
        roleMenu[index2].forEach(e => {
            // e.meta.toPath = e.path
            e.props = true
            router.addRoute('index', e)
        })
        if (to.redirectedFrom != undefined) {
            next({path: to.redirectedFrom?.fullPath, replace: true});
        } else {
            next({...to, replace: true});
        }
    } else {
        next()
    }
})
export default router