一、import写法 报错
function loadPageByRoutes(str) { // 传入的str为 '@/views/Home.vue' 这种格式 return () => import(`${str}`) // 要报错 }
二、改为require写法,并返回一个resolve ,可行
function loadPageByRoutes(str) { // views文件夹下的Home组件,传入的格式为 'Home' return function (resolve) { require([`@/views/${str}.vue`], resolve) } }
三,完整方法
代码:
function loadPageByRoutes (str) { return function (resolve) { require([`@/views/${str}.vue`], resolve) } } // 遍历后台传来的路由字符串,转换为组件对象 function filterAsyncRouter (asyncRouterMap) { const accessedRouters = asyncRouterMap.filter(route => { if (route.component) { if (route.component === 'Layout') { route.component = Layout } else { route.component = loadPageByRoutes(route.component) } } if (route.children && route.children.length) { route.children = filterAsyncRouter(route.children) } return true }) return accessedRouters }
路由返回格式:
这里注意根节点path 加 / ,子节点不加 /
具体动态路由实现参考:https://www.jianshu.com/p/4f2566b67989?from=singlemessage