vue3 addRoute 动态添加路由

39 篇文章 0 订阅

vue3 动态添加路由 删除动态路由

动态添加路由

/**
 * 前置导航守卫
 * 动态添加路由   刷新消失
 * A 前端 全部配置好  meta: { roles: ['0'] } 通过 roles匹配
 * 修改时  前端也要同步修改
 *
 * B 数据全部由 后台提供   完全动态渲染
 * 1 登录页 中  获取 MenuList  中包含  router 存入 vuex
 * 2 beforeEach  中 添加动态路由
 * 指定 部分页面 不参与 动态添加  目前 '/login'
 * 静态路由的数量 === 路由栈的数量  说明首次 添加
 * next({ path: "/home", replace: true })--二级路由 首页为 /home
 * 必须指定 path: "/home" 初始化时 二级路由首页才会展示  相当于 跳转两次
 *
 * next({}) 修改  相当于 重定向  所以会再次进入 beforeEach
 * 如果还是 next({})  相当于 再次 路由跳转  直到遇到 next() 停止
 * 无论怎么  跳转  最后一定要 原生 的 next() 停止
 */
const filterRoutes = ['/login']
router.beforeEach(async (to, from, next) => {
	console.log(to)
	console.log(router.getRoutes().length)
	// console.log(router.options.routes, router.getRoutes())
	// 在 主页路由中  才 动态添加
	if (!filterRoutes.includes(to.path)) {
		// 静态路由的数量 === 路由栈的数量 children存在 说明首次 添加
		if (router.getRoutes().length <= 3) {
			const list = await asyncMenuList()
			list.forEach(route => router.addRoute('mainHome', route))
			next({ path: to.path, replace: true })
		}
		next()
	} else {
		// 直接放行
		next()
	}
})
// vuex dispatch menuList
const asyncMenuList = async () => {
	const data = await store.dispatch('common/getMenuList')
	return dynamicAddRoutes(data)
}
// 动态 添加 routes
const dynamicAddRoutes = MenuList => {
	// const MenuList = store.state.common.menuList
	const routes = []
	MenuList.forEach(item => {
		if (!item.children) {
			routes.push({
				path: item.path,
				name: item.name,
				component: () => import(`@/views${item.url}`),
			})
		} else {
			item.children.forEach(item => {
				item.obj.forEach(item => {
					routes.push({
						path: item.path,
						name: item.name,
						component: () => import(`@/views${item.url}`),
					})
				})
			})
		}
	})
	// vuex更改动态路由
	store.commit('common/setRouteList', routes)
	return routes

删除动态路由

// 重置
export const resetRouter = () => {
	const routes = store.state.common.routeList
	routes && routes.forEach(route => router.removeRoute(route.name))
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值