当前位置: 首页 > Web前端 > vue.js

vue动态路由加载

时间:2023-04-01 00:29:37 vue.js

/*Convention:directoryresults产生的路由信息??目录结构如下directory1--directory2--directory3--page生成的路由路径为:directory1/directory2/directory3/page如果page被命名和index.vue,会截取并生成路径:目录1/目录2/目录3。推荐目录层次如下:业务目录--模块目录--页面此时生成的路径为:业务目录/module目录/页面,同时使用Layout布局(包括Menu和navigation)路径只有一层时,不会使用Layout布局,比如页面目录(home)--page(名为index.vue)文件包含目录下的组件不会产生路由信息*///主页不需要Layout//重定向//404//views是src下页面所在目录//获取所有路由信息letallFiles=[]constcontexts=require.context('@/views',true,/^(?!.*?components).*\.vue$/,'lazy',)contexts.keys().forEach(file=>{allFiles.push(file)})//console.log('allFiles',allFiles)从'@/layout/Layout2'导入布局letroutes=[]allFiles.forEach(file=>{letpath=file.substring(1).replace('/index.vue','').replace('.vue','')letname=path.substring(1).replace(/\//g,'-')let_filePath=file.replace('./','')letcomponent=loader(_filePath)//console.log(path)letarray=path.split('/')//console.log(array.length,path)if(array.length<2){return}//当前目录不使用Layoutif(array.length===2){letroute={path,component,name,}routes.push(route)return}path=path.replace(`/${array[1]}/`,'')//没有布局的全屏if(array[1]==='fullScreen'){letroute={path:`/fullScreen/${path}`,component,name,}routes.push(route)}else{//多层目录应用Layoutletroute={path:`/${array[1]}`,component:Layout,children:[{path,component,name}],}routes.push(route)}})constredirect=[//首页重定向{path:'/',redirect:'/home',},{path:'/502',redirect:'/fullScreen/502',},//404{path:'*',redirect:'/fullScreen/404',},]//添加重定向routes.push(...redirect)//console.log('routes',routes)//import(///*webpackChunkName:'[request]'*///`@/views/${file}`//)函数加载器(文件){return()=>import(`@/views/${file}`)}importVuefrom'vue'importRouterfrom'vue-router'Vue.use(Router)exportletrouter=newRouter({//mode:'history',scrollBehavior:()=>({y:0}),routes:routes,})importstorefrom'@/store/index'router.beforeEach((to,from,next)=>{//防止用户手动清除导航的本地存储if(!localStorage.getItem('boxCategoryDataLocal')){localStorage.setItem('boxCategoryDataLocal','21212')next({path:'/'})return}//url切换时,切换上下文,获取上下文从url和SwitchcontextletcontextName=to.path.split('/')[1]if(store.getters.allContainers[contextName]&&contextName!==store.getters.currentContainer.contextName){store.dispatch('changeContext',contextName)next()return}//一些公共页面,比如common,找不到对应的容器对象//此时不会切换上下文,当前不做任何处理next()})从'view-design'router.on导入{Modal}Error(error=>{console.log('Publishederrorcode:',error.message)constpattern=/Loadingchunk(.)+failed/gconstisChunkLoadFailed=error.message.match(pattern)if(isChunkLoadFailed){Modal.error({title:'提示',content:'网站已更新,请刷新页面',okText:'Refresh',onOk:()=>{location.reload()},})}})//修复跳转时推送相同地址会报错的问题constoriginalPush=Router.prototype.pushRouter.prototype.push=functionpush(location){returnoriginalPush.call(this,location).catch(err=>err)}