vue3使用动态加载路由
动态加载路由来判断权限问题,根据后端接口判断是否显示该路由
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()方法来动态改变路由
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)