//异步路由(需要权限的页面) export const asyncRouterMap = [ { path: '/resource', name: 'nav.Resource', meta: { permission: [] }, component: (resolve) => require(['@/components/Resource/resource'], resolve) }, { path: '/template', name: 'nav.Template', meta: { permission: [] }, component: (resolve) => require(['@/components/Template/template'], resolve) }, { path: '/generalSet', name: 'nav.System', meta: { permission: [] }, component: (resolve) => require(['@/components/SystemSet/generalSet'], resolve) }, { path: '', name: 'nav.Log', component: App, children: [ { path: '/userLog', name: 'nav.UserLog', meta: { permission: [] }, component: (resolve) => require(['@/components/Log/userLog'], resolve), }, { path: '/operatingLog', name: 'nav.SystemLog', meta: { permission: [] }, component: (resolve) => require(['@/components/Log/operatingLog'], resolve), }, ] } ] ];
为每个路由页面增加meta字段。在routerMatch函数中将匹配到的详细权限字段赋值到这里。这样在每个页面的route对象中就会得到这个字段。
asyncRouter.find((s) => { if (s.path === '') { s.children.find((y) => { if (y.path === path) { //赋值 y.meta.permission = item.permission; routers.push(s); } }) } if (s.path === path) { s.meta.permission = item.permission; routers.push(s); } })
接下来我们编写一个vue自定义指令对页面中需要进行鉴权的元素进行判断,比如类似这样的:
<a @click="upload" v-allow="'3'"></a> /* 3代表一个上传权限的ID,权限中有3则显示按钮 */
我们直接注册一个全局指令,利用vnode来访问vue的方法。代码如下:
//main.js //按扭权限指令 Vue.directive('allow', { inserted: (el, binding, vnode) => { let permissionList = vnode.context.$route.meta.permission; if (!permissionList.includes(binding.value)) { el.parentNode.removeChild(el) } } })
至此为止,权限控制流程就已经完全结束了,在最后我们再看一下完整的权限控制流程图吧.
五、路由控制完整流程图