简单介绍前后端工作
后端主要是三张表:用户表、路由表、角色-权限表
-
注意,一般后端不做数据结构化,只是返回前端所需要的数据
-
前端拿到后端的数据需要改变成tree模型
1、uid -> 后端API - 路由权限API
2、后端 -> 用户对应的路由权限列表 -> 前端 -> json
3、json -> 树形结构化
4、树形结构化的数据 -> vue路由结构
5、路由结构动态 -> 静态路由
6、树形结构化的数据 -> 菜单组件
//后端返回的json格式
{
id:1,
pid:3, //父节点
path:,
name:,
link:,
title:
},
{
id:2,
pid:3,
path:,
name:,
link:,
title:
}
·····
前端向后端要该角色的权限列表id,前端根据权限id列表来动态渲染路由,
具体操作
前端拿到的数据
前端将数据树形结构化
/**
* 将后端传来的路由列表树形结构化
*/
let data = [
{
id: 2,
pid: 0,
path: "/course",
name: "Course",
title: "课程管理",
},
{
id: 3,
pid: 2,
path: "operate",
name: "CourseOperate",
link: "/course/operate",
title: "课程操作",
},
{
id: 4,
pid: 3,
path: "info_data",
name: "CourseInfoData",
link: "/course/operate/info_data",
title: "课程数据",
},
{
id: 5,
pid: 2,
path: "add",
name: "CourseAdd",
link: "/course/add",
title: "添加课程",
},
{
id: 6,
pid: 0,
path: "/student",
name: "Student",
title: "学生管理",
},
{
id: 7,
pid: 6,
path: "operate",
name: "StudentOperate",
link: "/student/operate",
title: "学生操作",
},
{
id: 8,
pid: 6,
path: "add",
name: "StudentAdd",
link: "/student/add",
title: "添加学生",
}
]
formatRouterTree(data)
function formatRouterTree (data) {
// 现将总结点分离,其余都当做子节点
let parent = data.filter(p => p.pid === 0),
children = data.filter(c => c.pid !== 0)
dataToTree(parent, children)
console.log(parent)
function dataToTree (parent, children) {
parent.map(p => {
children.map((c, i) => {
if (c.pid === p.id) {
let _c = JSON.parse(JSON.stringify(children)) //深拷贝--保存一份children
_c.splice(i, 1) //删除自己保留其他children
dataToTree([c], _c) //剩余的继续递归
if (p.children) {
p.children.push(c)
} else {
p.children = [c]
}
}
})
})
}
return parent
}
进一步转化为路由结构的tree结构
// 转化为路由表格式
function generateRouter (UserRouter) {
let newRouter = UserRouter.map(r => {
let routes = {
path: r.path,
name: r.name,
component: () => import(`@/views/${r.name}`)
}
if (r.children) {
routes.children = generateRouter(r.children)
}
return routes
})
console.log(newRouter)
return newRouter
}
在全局路由守卫中动态加入路由
// 路由守卫
router.beforeEach(async (to, from, next) => {
if (!store.state.hasAuth) {
// 没有权限信息时
await store.dispatch('setUserRouters')
const newRoutes = generateRouter(store.state.userRouters)
console.log("🚀 ~ file: main.js:20 ~ router.beforeEach ~ newRoutes", newRoutes)
// router.addRoutes(newRoutes) //显示已经弃用
newRoutes.map((item) => {
router.addRoute(item)
})
next({ path: to.path })
} else {
// 有权限时
next()
}
})