今天在使用vue动态加载菜单,报了这个错:

Uncaught (in promise) ChunkLoadError: Loading chunk 28 failed.
(missing: http://localhost:8080/sal/js/28.js)
    at Function.requireEnsure [as e] (app.js:896)
    at Function.fn.e (app.js:177)
    at component (menu.js?2971:47)
    at eval (vue-router.esm.js?8c4f:2144)
    at eval (vue-router.esm.js?8c4f:2171)
    at Array.map (<anonymous>)
    at eval (vue-router.esm.js?8c4f:2171)
    at Array.map (<anonymous>)
    at flatMapComponents (vue-router.esm.js?8c4f:2170)
    at eval (vue-router.esm.js?8c4f:2106)

我的菜单menu.js如下:

import {getRequest} from './api'  
export const initMenu = (router,store) => {  
    if(store.state.routes.length > 0 ){  
        return;
    }
    getRequest("/system/cfg/getMenu").then(data => {  //如果routes为空,则初始化菜单
       if(data){
          
           let fmtRoutes = formatRoutes(data.obj);  //格式化router
           for(var i = 0 ; i < fmtRoutes.length ; i += 1 ){
               const route = fmtRoutes[i];
               router.addRoute(route)
           }
           //router.addRoutes(fmtRoutes); //添加到路由 addRoutes已经废弃
           store.commit('initRoutes',fmtRoutes); //将数据存入vuex
       }
    })

}
export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach((router) => {
        let  {       //将返回的对象封装(定义匿名对象,并将router的值赋给它)
            path,
            component,
            name,
            iconCls,
            children
        } = router;

        if(children && children instanceof Array){
            children = formatRoutes(children);
        }
        let fmRouter = {       //temp对象
            path:path,
            name:name,
            iconCls:iconCls,
            children:children,
            component(resolve){    //等效于component: function conponent(resolve){},通过函数获取值
                if(component.startsWith('Home')){
                    require(['../view/' + component +'.vue'],resolve);
                }else if(component.startsWith('Emp')){
                    require(['../view/emp/' + component +'.vue'],resolve);
                }else if(component.startsWith('Per')){
                    require(['../view/per/' + component +'.vue'],resolve);   
                }else if(component.startsWith('Sal')){
                    require(['../view/sal/' + component +'.vue'],resolve); 
                }else if(component.startsWith('Sta')){
                    require(['../view/sta/' + component +'.vue'],resolve);    
                }else if(component.startsWith('Sys')){
                    require(['../view/sys/' + component +'.vue'],resolve);
                }
                
            }
        }
        fmtRoutes.push(fmRouter);
    });
    return fmtRoutes;
}

当我点击二级菜单员工奖惩的时候报错
在这里插入图片描述
查找原因是因为require加载component方式为懒加载,懒加载的时候用history路由模式,就会出现这种错误。

在router里面注释掉history路由模式,改用默认的hash模式。重新启动项目,程序运行成功。
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐