动态路由+用户权限路由篇
1、实现思路
实现动态路由前提是服务端做好Router路由表的返回数据格式,一般分为两种情况(本人见识少,目前只遇到这两种)一是服务端返回客户端登录用户的权限ID数组,客户端通过权限ID修改对应路由的hidden属性选择是否展示,同时在router.beforeEach中判断好每次路由跳转的目标地址是否符合权限信息,防止通过地址栏输入方式跳转;二是前端配置好login,home等基础通用路由,再由服务端返回完整路由表,通过解析路由数据,动态添加至路由表中。
2、本文主要讲述上述第二种方式如何实现动态路由
步骤:从login页跳转home时,获取数据存储在pinia中,beforeEach前置钩子解析pinia中的数据,动态添加至路由表。
(1)配置:vue3 +typeScript+pinia+mock
基础配置如何引入就不过多阐述,进入代码部分。
Router基础路由表
{
path: "/",
redirect: "/login"
},
{
path: "/login",
name: "Login",
meta: { title: "登录", },
component: () => import("../views/login/LoginView.vue"),
},
{
path: "/home",
name: "home",
redirect: "/home/homepage",
component: () => import("../views/home/HomeView.vue"),
children: [
{
path: "/home/homepage",
name: "homepage",
meta: { title: "首页", icon: "icon-shouye", hidden: false, role: ['root', 'user'] },
component: () => import("../views/homepage/index.vue"),
}
]
}
mock数据
router: [
{
path: "/home/echarts",
name: "echarts",
meta: { title: "图表", icon: "icon-tubiao-zhexiantu", hidden: false },
component: "/echarts/index",
},
{
path: "/home/error",
name: "error",
meta: { title: "错误页", icon: "icon-cuowuyemian", hidden: false },
redirect: "/error/404",
component: '/error/index',
children: [
{
path: "/home/er