欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

动态路由

程序员文章站 2022-06-03 18:26:44
...

新建util.js

export const initMenu = (router, store) => {					/**异步添加路由**/
	return new Promise((resolve,reject)=>{
		console.log('刷新2')
		let menuRoutes = JSON.parse(localStorage.getItem('user'))[4].children
		var fmtRoutes = formatRoutes(menuRoutes)
		// router.options.routes = fmtRoutes
		router.addRoutes(fmtRoutes);
		console.log(fmtRoutes)
		store.commit('initMenu', fmtRoutes)
		resolve(router);
	})
}

export const formatRoutes = (routes) => {
	let fmRoutes = [];
	routes.forEach(router => {
		// debugger
		let path = router.menuURL
		let component = router.component
		let name = router.name_y
		let meta = {
			keepAlive: router.keepAlive,
			needLogin: true,
			name: router.catalogName,
			icon: router.icon,
		}
		let hidden = router.hidden
		let children = router.children || []
		let icon = router.icon
		if (router.hasChildren) {
			children = formatRoutes(children);
		}
		let fmRouter = {
			path: path,
			component(resolve) {
				let componentPath = ''
				if (name === 'System') {
					require(['@/views/System'], resolve)
					return
				} else if(name==='MgLog'){
					require(['@/views/sys/LogManage.vue'], resolve)
					return
				}else if(name==='MgPriv'){
					require(['@/views/sys/PrivilegeManagement'], resolve)
					return
				}else if(name==='Organ'){
					require(['@/views/sys/OrganizationStructure'], resolve)
					return
				}else if(name==='MgRole'){
					require(['@/views/sys/RoleManagement'], resolve)
					return
				}else if(name==='MgUser'){
					require(['@/views/sys/UserManagement'], resolve)
					return
				}
			},
			name: name,
			meta: meta,
			hidden: hidden,
			children: children
		}
		// debugger
		fmRoutes.push(fmRouter);
	})
	console.log(fmRoutes, '^^^^')
	return fmRoutes;
}

main.js设置Route的beforeEach
```javascript
router.beforeEach((to, from, next) => {
	let userinform = store.state.userinform
	if(store.state.routes.length>0){
	}else{
		initMenu(router,store).then((router)=>{
			let path = location.href.split('#')[1]
			router.push({
				path:path			/**刷新以后使用网上推荐无效,发现刷新以后路由无定向,重新手动定向**/
			})
		})
		
	}
	console.log(to)
	if (to.meta.needLogin) {
		if (userinform == "未登录") {
			next({
				name: 'Login'
			})
		}
		else {
			store.dispatch('UpdataPathName',to.name)
			next()
			return
			
		}
	}
	else {
		if(to.name=='Login'){
			store.commit('Logout')
		}
		store.dispatch('UpdataPathName',to.name)
		next()
	}
})
store =>index.js
将路由存入vuex,动态渲染侧边栏。本来打算使用router.options.routes,发现通过addRoutes添加的routes获取不到,官方也给出了说明,防止与默认路由冲突,所以使用vuex渲染
```javascript
initMenu(state,data){
			state.routes = data
		},

欢迎提意见,以及改进方案

相关标签: vue