本篇文章為大家展示了怎么在vue中實現(xiàn)權(quán)限路由,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
創(chuàng)新互聯(lián)公司服務項目包括宜州網(wǎng)站建設(shè)、宜州網(wǎng)站制作、宜州網(wǎng)頁制作以及宜州網(wǎng)絡營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,宜州網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務的客戶以成都為中心已經(jīng)輻射到宜州省份的部分城市,未來相信會繼續(xù)擴大服務區(qū)域并繼續(xù)獲得客戶的支持與信任!
實現(xiàn)
前端定義好路由,并且在路由上標記相應的權(quán)限信息
const routerMap = [ { path: '/permission', component: Layout, redirect: '/permission/index', alwaysShow: true, // will always show the root menu meta: { title: 'permission', icon: 'lock', roles: ['admin', 'editor'] // you can set roles in root nav }, children: [{ path: 'page', component: () => import('@/views/permission/page'), name: 'pagePermission', meta: { title: 'pagePermission', roles: ['admin'] // or you can only set roles in sub nav } }, { path: 'directive', component: () => import('@/views/permission/directive'), name: 'directivePermission', meta: { title: 'directivePermission' // if do not set roles, means: this page does not require permission } }] }]
全局路由守衛(wèi)每次都判斷用戶是否已經(jīng)登錄,沒有登錄則跳到登錄頁。已經(jīng)登錄(已經(jīng)取得后臺返回的用戶的權(quán)限信息(角色之類的)),則判斷當前要跳轉(zhuǎn)的路由,用戶是否有權(quán)限訪問(根據(jù)路由名稱到全部路由里找到對應的路由,判斷用戶是否具備路由上標注的權(quán)限信息(比如上面的roles: ['admin', 'editor']))。沒有權(quán)限則跳到事先定義好的界面(403,404之類的)。
這種方式,菜單可以直接用路由生成(用戶沒有權(quán)限的菜單也會顯示,點擊跳轉(zhuǎn)的時候才做權(quán)限判斷),也可以在用戶登錄后根據(jù)用戶權(quán)限把路由過濾一遍生成菜單(菜單需要保存在vuex里)。
目前iview-admin還是用的這種方式
缺點
加載所有的路由,如果路由很多,而用戶并不是所有的路由都有權(quán)限訪問,對性能會有影響。
全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做權(quán)限判斷。
菜單信息寫死在前端,要改個顯示文字或權(quán)限信息,需要重新編譯
菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,而且路由不一定作為菜單顯示,還要多加字段進行標識
登錄頁與主應用分離
針對前一種實現(xiàn)方式的缺點,可以將登錄頁與主應用放到不同的頁面(不在同一個vue應用實例里)。
實現(xiàn)
登錄成功后,進行頁面跳轉(zhuǎn)(真正的頁面跳轉(zhuǎn),不是路由跳轉(zhuǎn)),并將用戶權(quán)限傳遞到主應用所在頁面,主應用初始化之前,根據(jù)用戶權(quán)限篩選路由,篩選后的路由作為vue的實例化參數(shù),而不是像前一種方式所有的路由都傳遞進去,也不需要在全局路由守衛(wèi)里做權(quán)限判斷了。
缺點
需要做頁面跳轉(zhuǎn),不是純粹的單頁應用
菜單信息寫死在前端,要改個顯示文字或權(quán)限信息,需要重新編譯
菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,而且路由不一定作為菜單顯示,還要多加字段進行標識
使用addRoutes動態(tài)掛載路由
addRoutes允許在應用初始化之后,動態(tài)的掛載路由。有了這個新姿勢,就不用像前一種方式那樣要在應用初始化之要對路由進行篩選。
實現(xiàn)
應用初始化的時候先掛載不需要權(quán)限控制的路由,比如登錄頁,404等錯誤頁。
有個問題,addRoutes應該何時調(diào)用,在哪里調(diào)用
登錄后,獲取用戶的權(quán)限信息,然后篩選有權(quán)限訪問的路由,再調(diào)用addRoutes添加路由。這個方法是可行的。但是不可能每次進入應用都需要登錄,用戶刷新瀏覽器又要登陸一次。
所以addRoutes還是要在全局路由守衛(wèi)里進行調(diào)用
import router from './router' import store from './store' import { Message } from 'element-ui' import NProgress from 'nprogress' // progress bar import 'nprogress/nprogress.css'// progress bar style import { getToken } from '@/utils/auth' // getToken from cookie NProgress.configure({ showSpinner: false })// NProgress Configuration // permission judge function function hasPermission(roles, permissionRoles) { if (roles.indexOf('admin') >= 0) return true // admin permission passed directly if (!permissionRoles) return true return roles.some(role => permissionRoles.indexOf(role) >= 0) } const whiteList = ['/login', '/authredirect']// no redirect whitelist router.beforeEach((to, from, next) => { NProgress.start() // start progress bar if (getToken()) { // determine if there has token /* has token*/ if (to.path === '/login') { next({ path: '/' }) NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it } else { if (store.getters.roles.length === 0) { // 判斷當前用戶是否已拉取完user_info信息 store.dispatch('GetUserInfo').then(res => { // 拉取user_info const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop'] store.dispatch('GenerateRoutes', { roles }).then(() => { // 根據(jù)roles權(quán)限生成可訪問的路由表 router.addRoutes(store.getters.addRouters) // 動態(tài)添加可訪問路由表 next({ ...to, replace: true }) // hack方法 確保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record }) }).catch((err) => { store.dispatch('FedLogOut').then(() => { Message.error(err || 'Verification failed, please login again') next({ path: '/' }) }) }) } else { // 沒有動態(tài)改變權(quán)限的需求可直接next() 刪除下方權(quán)限判斷 ↓ if (hasPermission(store.getters.roles, to.meta.roles)) { next()// } else { next({ path: '/401', replace: true, query: { noGoBack: true }}) } // 可刪 ↑ } } } else { /* has no token*/ if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入 next() } else { next('/login') // 否則全部重定向到登錄頁 NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it } } }) router.afterEach(() => { NProgress.done() // finish progress bar })
關(guān)鍵的代碼如下
if (store.getters.roles.length === 0) { // 判斷當前用戶是否已拉取完user_info信息 store.dispatch('GetUserInfo').then(res => { // 拉取user_info const roles = res.data.roles // note: roles must be a array! such as: ['editor','develop'] store.dispatch('GenerateRoutes', { roles }).then(() => { // 根據(jù)roles權(quán)限生成可訪問的路由表 router.addRoutes(store.getters.addRouters) // 動態(tài)添加可訪問路由表 next({ ...to, replace: true }) // hack方法 確保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record }) }).catch((err) => { store.dispatch('FedLogOut').then(() => { Message.error(err || 'Verification failed, please login again') next({ path: '/' }) }) })
上面的代碼就是vue-element-admin的實現(xiàn)
缺點
全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
菜單信息寫死在前端,要改個顯示文字或權(quán)限信息,需要重新編譯
菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標題,圖標之類的信息,而且路由不一定作為菜單顯示,還要多加字段進行標識
菜單與路由分離,菜單由后端返回
菜單的顯示標題,圖片等需要隨時更改,要對菜單做管理功能。
后端直接根據(jù)用戶權(quán)限返回可訪問的菜單。
實現(xiàn)
前端定義路由信息(標準的路由定義,不需要加其他標記字段)。
{ name: "login", path: "/login", component: () => import("@/pages/Login.vue") }
name字段都不為空,需要根據(jù)此字段與后端返回菜單做關(guān)聯(lián)。
做菜單管理功能的時候,一定要有個字段與前端的路由的name字段對應上(也可以是其他字段,只要菜單能找到對應的路由或者路由能找到對應的菜單就行),并且做唯一性校驗。菜單上還需要定義權(quán)限字段,可以是一個或多個。其他信息,比如顯示標題,圖標,排序,鎖定之類的,可以根據(jù)實際需求進行設(shè)計。
還是在全局路由守衛(wèi)里做判斷
function hasPermission(router, accessMenu) { if (whiteList.indexOf(router.path) !== -1) { return true; } let menu = Util.getMenuByName(router.name, accessMenu); if (menu.name) { return true; } return false; } Router.beforeEach(async (to, from, next) => { if (getToken()) { let userInfo = store.state.user.userInfo; if (!userInfo.name) { try { await store.dispatch("GetUserInfo") await store.dispatch('updateAccessMenu') if (to.path === '/login') { next({ name: 'home_index' }) } else { //Util.toDefaultPage([...routers], to.name, router, next); next({ ...to, replace: true })//菜單權(quán)限更新完成,重新進一次當前路由 } } catch (e) { if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入 next() } else { next('/login') } } } else { if (to.path === '/login') { next({ name: 'home_index' }) } else { if (hasPermission(to, store.getters.accessMenu)) { Util.toDefaultPage(store.getters.accessMenu,to, routes, next); } else { next({ path: '/403',replace:true }) } } } } else { if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進入 next() } else { next('/login') } } let menu = Util.getMenuByName(to.name, store.getters.accessMenu); Util.title(menu.title); }); Router.afterEach((to) => { window.scrollTo(0, 0); });
上面代碼是vue-quasar-admin的實現(xiàn)。因為沒有使用addRoutes,每次路由跳轉(zhuǎn)的時候都要判斷權(quán)限,這里的判斷也很簡單,因為菜單的name與路由的name是一一對應的,而后端返回的菜單就已經(jīng)是經(jīng)過權(quán)限過濾的,所以如果根據(jù)路由name找不到對應的菜單,就表示用戶有沒權(quán)限訪問。
如果路由很多,可以在應用初始化的時候,只掛載不需要權(quán)限控制的路由。取得后端返回的菜單后,根據(jù)菜單與路由的對應關(guān)系,篩選出可訪問的路由,通過addRoutes動態(tài)掛載。
缺點
菜單需要與路由做一一對應,前端添加了新功能,需要通過菜單管理功能添加新的菜單,如果菜單配置的不對會導致應用不能正常使用
全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
菜單與路由完全由后端返回
菜單由后端返回是可行的,但是路由由后端返回呢?看一下路由的定義
{ name: "login", path: "/login", component: () => import("@/pages/Login.vue") }
后端如果直接返回
{ "name": "login", "path": "/login", "component": "() => import('@/pages/Login.vue')" }
這是什么鬼,明顯不行。() => import('@/pages/Login.vue')這代碼如果沒出現(xiàn)在前端,webpack不會對Login.vue進行編譯打包
實現(xiàn)
前端統(tǒng)一定義路由組件,比如
const Home = () => import("../pages/Home.vue"); const UserInfo = () => import("../pages/UserInfo.vue"); export default { home: Home, userInfo: UserInfo };
將路由組件定義為這種key-value的結(jié)構(gòu)。
后端返回格式
[ { name: "home", path: "/", component: "home" }, { name: "home", path: "/userinfo", component: "userInfo" } ]
在將后端返回路由通過addRoutes動態(tài)掛載之間,需要將數(shù)據(jù)處理一下,將component字段換為真正的組件。
至于菜單與路由是否還要分離,怎么對應,可以根據(jù)實際需求進行處理。
如果有嵌套路由,后端功能設(shè)計的時候,要注意添加相應的字段。前端拿到數(shù)據(jù)也要做相應的處理。
缺點
全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
前后端的配合要求更高
不使用全局路由守衛(wèi)
前面幾種方式,除了登錄頁與主應用分離,每次路由跳轉(zhuǎn),都在全局路由守衛(wèi)里做了判斷。
實現(xiàn)
應用初始化的時候只掛載不需要權(quán)限控制的路由
const constRouterMap = [ { name: "login", path: "/login", component: () => import("@/pages/Login.vue") }, { path: "/404", component: () => import("@/pages/Page404.vue") }, { path: "/init", component: () => import("@/pages/Init.vue") }, { path: "*", redirect: "/404" } ];
export default constRouterMap; import Vue from "vue"; import Router from "vue-router"; import ConstantRouterMap from "./routers"; Vue.use(Router); export default new Router({ // mode: 'history', // require service support scrollBehavior: () => ({ y: 0 }), routes: ConstantRouterMap });
登錄成功后跳到/路由
submitForm(formName) { let _this=this; this.$refs[formName].validate(valid => { if (valid) { _this.$store.dispatch("loginByUserName",{ name:_this.ruleForm2.name, pass:_this.ruleForm2.pass }).then(()=>{ _this.$router.push({ path:'/' }) }) } else { return false; } }); }
因為當前沒有/路由,會跳到/404
<template> <h2>404</h2> </template> <script> export default { name:'page404', mounted(){ if(!this.$store.state.isLogin){ this.$router.replace({ path: '/login' }); return; } if(!this.$store.state.initedApp){ this.$router.replace({ path: '/init' }); return } } } </script>
404組件里判斷已經(jīng)登錄,接著判斷應用是否已經(jīng)初始化(用戶權(quán)限信息,可訪問菜單,路由等是否已經(jīng)從后端取得)。沒有初始化則跳轉(zhuǎn)到/init路由
<template> <div></div> </template> <script> import { getAccessMenuList } from "../mock/menus"; import components from "../router/routerComponents.js"; export default { async mounted() { if (!this.$store.state.isLogin) { this.$router.push({ path: "/login" }); return; } if (!this.$store.state.initedApp) { const loading = this.$loading({ lock: true, text: "初始化中", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)" }); let menus = await getAccessMenuList(); //模擬從后端獲取 var routers = [...menus]; for (let router of routers) { let component = components[router.component]; router.component = component; } this.$router.addRoutes(routers); this.$store.dispatch("setAccessMenuList", menus).then(() => { loading.close(); this.$router.replace({ path: "/" }); }); return; } else { this.$router.replace({ path: "/" }); } } }; </script>
init組件里判斷應用是否已經(jīng)初始化(避免初始化后,直接從地址欄輸入地址再次進入當前組件)。
如果已經(jīng)初始化,跳轉(zhuǎn)/路由(如果后端返回的路由里沒有定義次路由,則會跳轉(zhuǎn)404)。
沒有初始化,則調(diào)用遠程接口獲取菜單和路由等,然后處理后端返回的路由,將component賦值為真正
的組件,接著調(diào)用addRoutes掛載新路由,最后跳轉(zhuǎn)/路由即可。菜單的處理也是在此處,看實際
需求。
實現(xiàn)例子
缺點
在404頁面做了判斷,感覺比較怪異
多引入了一個init頁面組件
上述內(nèi)容就是怎么在vue中實現(xiàn)權(quán)限路由,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
新聞標題:怎么在vue中實現(xiàn)權(quán)限路由
轉(zhuǎn)載源于:http://sd-ha.com/article44/ghsehe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、動態(tài)網(wǎng)站、域名注冊、網(wǎng)頁設(shè)計公司、自適應網(wǎng)站、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)