addRoutes动态添加路由

761 阅读1分钟
import router from '../router'import Layout from '@/layout/index'export function getAsyncRoutes(routerList) {    let newArr = routerList.filter(item => item.path !== "dashboard")    return new Promise((resolve, reject) => {
        //将代码拼成想要的格式        let asyncRouters = handleComp(newArr, true, null)
           //路由404拦截必须添加在路由表最末尾的位置        asyncRouters.push({ path: '*', redirect: '/error/404', hidden: true })        asyncRouters.forEach(item => {
        //划重点:必须先push进router.options.routes---然后再执行addRoutes            router.options.routes.push(item)        })        // 加这一步才能渲染页面        router.addRoutes(asyncRouters)        resolve()    })}
//将代码拼成想要的格式--具体实现
function handleComp(routerList, isRoot, fatherPath) {    routerList.map((item) => {        if (isRoot) {            Object.assign(item, {                component: Layout,                path: '/' + item.path            })            if (!item.children) {                let obj = {                    component: loadView(item.path + item.path),                    path: '',                    meta: {                        title: item.meta.title                    }                }                let children = [];                children.push(obj)                Object.assign(item, {                    children: children                })            }        } else {            Object.assign(item, {                component: loadView(fatherPath + '/' + item.path)            })        }        if (item.children) {            handleComp(item.children, false, item.path)            return        }        // console.log(item)        return item    })    return routerList}
//路由懒加载导入路由文件
function loadView(view) {    return () => import(`@/views${view}`)}

注意:方法在登陆后调用,将数据按照自己想要的存储在本地缓存,刷新在app.vue再执行一次方法,重新渲染动态路由。

         在实现过程中遇到了问题:因为传参是一个数组对象,在修改对象属性值的时候会存在深度克隆的问题,导致后面的数据结构发生问题。