楠丶nan 2021-07-28 17:07 采纳率: 100%
浏览 296
已结题

Vue动态添加路由刷新的问题

最近在研究动态添加路由菜单,菜单添加过滤什么都写好了,就在路由守卫拦截那一块出现了问题。动态路由数据存储在store内,用于判断是否刷新页面,后端拿取的菜单存在cookie内,这是我的代码:

添加路由的代码
export function addUserMenus() {
    let menuList = getTrees(cookie.getJSON('menu'));
    const addRoutes = [];
    let tempList = [];
    menuList.forEach(item1 => {
        tempList = []
        let parent = {
            path: item1.url,
            name: item1.comName,
            component: () => import('@/views/system/' + item1.comName + '.vue')
        }
        let child = {
            path: '',
            name: '',
            component: null
        }
        if (item1.children) {
            item1.children.forEach(item2 => {
                child.path = item2.url;
                child.name = item2.comName;
                child.component = () => import('@/views/system/' + item2.comName + '.vue');
                tempList.push(child);
            })
        }
        if (tempList.length > 0) {
            addRoutes.push(Object.assign({}, parent, {
                children: tempList
            }))
        } else {
            addRoutes.push(parent);
        }
    })
    addRoutes.forEach(item => {
        router.addRoute('Home', item);
    })
    store.commit('setMenuRouter', addRoutes);
    console.info("初始", router.getRoutes())
}

//全局路由拦截
router.beforeEach((to, from, next) => {
    if (to.path == '/login') {
        if (cookie.get('user') != null || cookie.get('menu') != null || cookie.get('token') != null) {
            if (store.getters.getMenuRouter.length === 0) {
                addUserMenus();
            }
            next("/home/info");
        }
        next();
    } else {
        if (cookie.get('user') == null || cookie.get('menu') == null || cookie.get('token') == null) {
            cookie.remove('user');
            cookie.remove('menu');
            cookie.remove('token');
            ElMessage.error("发生异常,请重新登录!");
            next("/login");
        } else {
            if (store.getters.getMenuRouter.length === 0) {
                addUserMenus();
            }
            next();
        }
    }
})

页面一刷新就跳到404,控制台打印显示我路由内有动态添加进去的路由,感觉是动态路由还没添加进静态路由内,就已经next() 放行了,也不太确定是不是这个问题,但是一点击404的返回就能正常浏览页面了,返回按钮是用router.push跳转的。

img

img

  • 写回答

1条回答 默认 最新

  • 楠丶nan 2021-07-29 17:20
    关注

    已解决

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月6日
  • 已采纳回答 7月29日
  • 创建了问题 7月28日

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)