Vue刷新页面,动态addRoutes添加路由,报错Maximum call stack size exceed Cannot read property 'matched' of undefined

Vue项目中,如果用户刷新页面,导致存入vuex中的菜单数据清空,所以需要从缓存获取。

但是发现,有时候会报错

"RangeError: Maximum call stack size exceeded"

Maximum call stack size exceeded

 Cannot read property 'matched' of undefined"

Cannot read property 'matched' of undefined

Vue刷新页面,动态addRoutes添加路由,报错Maximum call stack size exceed Cannot read property 'matched' of undefined

Maximum call stack size exceeded 这段话报错栈溢出,一般是递归函数没有终止,不断的运行下去,但是我发现我的递归方法并没有问题,已经做了判断,但是还是会报错。

然后发现就是 addRoutes 动态添加vue路由 (点击可查看Vue官网的addRoutes的文档说明)的时候就报错了。但是就是不知道报什么错。

Vue刷新页面,动态addRoutes添加路由,报错Maximum call stack size exceed Cannot read property 'matched' of undefined

一直考虑了好久都没有发现问题,最终在大牛的帮助下解决了。

解决方法:

只需要把 redirect: '/index' 注释了就可以解决了。

原因:

去掉重定向,否则访问index,重定向到index,又重定向index,从而进入了死循环,而导致了栈溢出。

/**
 * 如果用户刷新页面,导致存入vuex中的菜单数据清空,需要从缓存获取;
 */
const menuData = JSON.parse(localStorage.getItem('menuData'));
if (menuData) {
    store.commit('ADD_MENU', menuData) // ?? commit or dispatch ,将缓存数据注入到store中
    const routes = mUtils.generateRoutesFromMenu(menuData) //根据菜单生成的路由信息
    const asyncRouterMap = [{
        path: '/index',
        name: '',
        hidden: true,
        component: require('./pages/home.vue').default,
        // redirect: '/index', //去掉重定向,否则访问index,重定向到index,又重定向index,死循环
        children: routes
    }]
    router.addRoutes(asyncRouterMap)
}