前言:關(guān)于vue權(quán)限路由的那些事兒……
項目背景:現(xiàn)有一個后臺管理系統(tǒng)溉委,共存在兩種類型的人員
①超級管理員(稱作admin)继谚,②普通用戶(稱作editor)
每種類型的人看到的操作欄并不一樣烈菌,可以進行的操作也不盡相同,于是就需要程序處理一下各個權(quán)限問題花履。
過程說難不難芽世,說簡單不算簡單
【迷茫的前期】
上百度、Google臭挽,狂搜了好多關(guān)于權(quán)限的問題捂襟,也許是仁者見仁智者見智吧,五花八門的介紹讓自己更加迷茫不堪欢峰,真心不知道從哪里下手:
1)讓后端返回關(guān)于權(quán)限的json數(shù)據(jù)吧葬荷,但卻不太懂這樣的數(shù)據(jù)應(yīng)該怎樣處理;
2)在前端路由那里處理纽帖,可是不明白應(yīng)該怎樣使用何種屬性來實現(xiàn)這個功能宠漩;
【最后】
最后看到一篇文章?手摸手,帶你用vue擼后臺 系列二(登錄權(quán)限篇)?懊直,但是發(fā)現(xiàn)代碼非常多權(quán)限功能是整合在框架里面的扒吁,傷心,我就想實現(xiàn)一個小小的權(quán)限功能室囊,沒辦法還是仔細的研究了起來雕崩。
具體實現(xiàn)思路
1 創(chuàng)建vue實例的時候?qū)ue-router掛載,但這個時候vue-router掛載一些登錄或者不用權(quán)限的公用的頁面融撞。
2 當用戶登錄后盼铁,獲取用role,將role和路由表每個頁面的需要的權(quán)限作比較尝偎,生成最終用戶可訪問的路由表饶火。
3 調(diào)用router.addRoutes(store.getters.addRouters)添加用戶可訪問的路由鹏控。
4 使用vuex管理路由表,根據(jù)vuex中可訪問的路由渲染側(cè)邊欄組件肤寝。
是不是有點懵沒關(guān)系下面我盡量用通俗點的話來講每一步
1在路由router.js里面聲明權(quán)限為admin的路由(異步掛載的路由asyncRouterMap)
// router.jsimport Vue from'vue'import Router from'vue-router'Vue.use(Router)exportconst constantRouterMap = [? {? ? path:'/',? ? redirect:'/login',? ? hidden:true},? {? ? path:'/login',? ? name:'登錄頁面',? ? hidden:true,? ? component: resolve => require(['../views/login/Login.vue'], resolve)? },? {? ? path:'/Readme',? ? // name:'Readmehome',? ? index:'Readme',? ? meta: {? ? ? title:'Readme',? ? ? icon:'el-icon-menu'},? ? component: resolve => require(['../components/common/Home.vue'], resolve),? ? children: [? ? ? {? ? ? ? name:'Readme',? ? ? ? path:'/',? ? ? ? meta: { title:'Readme', icon:'el-icon-menu'},? ? ? ? component: resolve => require(['../components/page/Readme.vue'], resolve)? ? ? }? ? ]? }]exportdefault new Router({? routes: constantRouterMap})// 異步掛載的路由// 動態(tài)需要根據(jù)權(quán)限加載的路由表exportconst asyncRouterMap = [? {? ? path:'/permission',? ? // name:'permissionhome',? ? meta: {? ? ? title:'permission',? ? ? icon:'el-icon-setting',? ? ? roles: ['admin']? ? },? ? component: resolve => require(['../components/common/Home.vue'], resolve),? ? children: [? ? ? {? ? ? ? name:'permission',? ? ? ? path:'/permission',? ? ? ? meta: {? ? ? ? ? title:'permission', icon:'el-icon-menu', roles: ['admin']? ? ? ? },? ? ? ? component: resolve => require(['../components/page/permission.vue'], resolve)? ? ? }? ? ]? },? { path:'*', redirect:'/404', hidden:true}]
這里我們根據(jù)?vue-router官方推薦?的方法通過meta標簽來標示改頁面能訪問的權(quán)限有哪些当辐。如meta: { role: ['admin','super_editor'] }表示該頁面只有admin和超級編輯才能有資格進入。
注意事項:這里有一個需要非常注意的地方就是 404 頁面一定要最后加載鲤看,如果放在constantRouterMap一同聲明了404缘揪,后面的所以頁面都會被攔截到404,詳細的問題見addRoutes when you've got a wildcard route for 404s does not work
2當用戶登錄后刨摩,獲取用role寺晌,將role和路由表每個頁面的需要的權(quán)限作比較,調(diào)用router.addRoutes(store.getters.addRouters)添加用戶可訪問的路由澡刹,生成最終用戶可訪問的路由表。路由表存在vuex里面
permission.js
// permission.jsimport router from'./router'import store from'./store'import { Message } from'element-ui'import { getToken } from'@/utils/auth'// 驗權(quán)const whiteList = ['/login','/authredirect'] // 不重定向白名單router.beforeEach((to, from, next) => {if(getToken()) { // 判斷是否有tokenif(to.path ==='/login') {? ? ? next({ path:'/'})? ? }else{if(store.getters.roles.length === 0) {? ? ? ? console.log('roles====0')? ? ? ? store.dispatch('GetInfo').then(res => { // 拉取用戶信息? ? ? ? ? const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop']? ? ? ? ? console.log('roles?', roles)? ? ? ? ? store.dispatch('GenerateRoutes', { roles }).then(() => { // 根據(jù)roles權(quán)限生成可訪問的路由表? ? ? ? ? ? console.log('addrouters', store.getters.addRouters)? ? ? ? ? ? router.addRoutes(store.getters.addRouters) // 動態(tài)添加可訪問路由表? ? ? ? ? ? next({ ...to, replace:true}) // hack方法 確保addRoutes已完成 ,setthe replace:trueso the navigation will not leave ahistoryrecord? ? ? ? ? })? ? ? ? }).catch(() => {? ? ? ? ? store.dispatch('FedLogOut').then(() => {? ? ? ? ? ? Message.error('驗證失敗,請重新登錄')? ? ? ? ? ? next({ path:'/login'})? ? ? ? ? })? ? ? ? })? ? ? }else{? ? ? ? console.log('====1')? ? ? ? next() // 當有用戶權(quán)限的時候耘婚,說明所有可訪問路由已生成 如訪問沒權(quán)限的全面會自動進入404頁面? ? ? }? ? }? }else{if(whiteList.indexOf(to.path) !== -1) {? ? ? next()? ? }else{? ? ? next('/login')? ? }? }})
3使用vuex管理路由表罢浇,根據(jù)vuex中可訪問的路由渲染側(cè)邊欄組件(菜單)。
最后預(yù)覽鏈接
源碼下載
https://github.com/mgbq/vue-permission
打賞 衷心的表示感謝
最后如有不對的麻煩指正