动态加载路由

动态加载路由,第1张

vue3使用动态加载路由

动态加载路由来判断权限问题,根据后端接口判断是否显示该路由

文章目录 `vue3使用动态加载路由`router.js中创建路由routerList文件夹存放默认路由信息使用router.beforeEach来加载总结


router.js中创建路由
import { createRouter, createWebHistory, createWebHashHistory } from "vue-router";
import routes from "./routesList.js"

const router = createRouter({
	history: createWebHashHistory(),
	routes
})


export default router;
routerList文件夹存放默认路由信息
import Home from "../view/Home.vue";
const routes = [
	{
		path: '/',
		redirect: '/login'
	},
	{
		path: "/Home",
		name: "Home",
		component: Home,
		children: [{
			path: "/dashboard",
			name: "dashboard",
			meta: {
				title: '系统首页'
			},
			component: () => import("../view/Dashboard.vue")
		}]
	}, 
	{
		path: "/login",
		name: "Login",
		meta: {
			title: '登录'
		},
		component: () => import("../view/Login.vue")
	}
]

export default routes;
使用router.beforeEach来加载
import router from './router/router'
import token from './utils/user'
import routes from './router/routerList'

router.beforeEach(async (to, from, next) => {
	if (token) { // 判断用户是否有token
		if (to.path === '/login') {
			next()
		} else {
			console.log(store.state.roles.length)
			if (store.state.roles.length === 0) {
				store.dispatch('userInfo').then(res => {
					// 动态路由
					console.log(res, 'userInfo')
					res.map(item => {
						if (item.child != null && item.child.length > 0) {
							item.child.map(item => {
								routes[1].children.push({
									path: item.urlPath,
									name: item.name,
									component: importView(item.urlPath),
									meta: {
										title: item.name,
									},
								})
							})
						}
					})
					routes.forEach(item => {
						router.addRoute(item)
					})
					next({ ...to, replace: true })
				})
			} else {
				next()
			}
		}
	} else {
		next('/login')
	}
})

function importView(view) {
	return () => Promise.resolve(require(`@/view${view}.vue`).default)
};


总结

使用beforeEach全局路由守卫结合vue.addRoute()方法来动态改变路由

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1322867.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存