国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

vue權(quán)限路由實(shí)現(xiàn)的方法示例總結(jié)

2019-11-19 13:23:45
字體:
供稿:網(wǎng)友

使用全局路由守衛(wèi)

實(shí)現(xiàn)

前端定義好路由,并且在路由上標(biāo)記相應(yīng)的權(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)限信息(角色之類的)),則判斷當(dāng)前要跳轉(zhuǎn)的路由,用戶是否有權(quán)限訪問(根據(jù)路由名稱到全部路由里找到對應(yīng)的路由,判斷用戶是否具備路由上標(biāo)注的權(quán)限信息(比如上面的roles: ['admin', 'editor']))。沒有權(quán)限則跳到事先定義好的界面(403,404之類的)。

這種方式,菜單可以直接用路由生成(用戶沒有權(quán)限的菜單也會顯示,點(diǎn)擊跳轉(zhuǎn)的時候才做權(quán)限判斷),也可以在用戶登錄后根據(jù)用戶權(quán)限把路由過濾一遍生成菜單(菜單需要保存在vuex里)。

目前iview-admin還是用的這種方式

缺點(diǎn)

  • 加載所有的路由,如果路由很多,而用戶并不是所有的路由都有權(quán)限訪問,對性能會有影響。
  • 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做權(quán)限判斷。
  • 菜單信息寫死在前端,要改個顯示文字或權(quán)限信息,需要重新編譯
  • 菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標(biāo)題,圖標(biāo)之類的信息,而且路由不一定作為菜單顯示,還要多加字段進(jìn)行標(biāo)識

登錄頁與主應(yīng)用分離

針對前一種實(shí)現(xiàn)方式的缺點(diǎn),可以將登錄頁與主應(yīng)用放到不同的頁面(不在同一個vue應(yīng)用實(shí)例里)。

實(shí)現(xiàn)

登錄成功后,進(jìn)行頁面跳轉(zhuǎn)(真正的頁面跳轉(zhuǎn),不是路由跳轉(zhuǎn)),并將用戶權(quán)限傳遞到主應(yīng)用所在頁面,主應(yīng)用初始化之前,根據(jù)用戶權(quán)限篩選路由,篩選后的路由作為vue的實(shí)例化參數(shù),而不是像前一種方式所有的路由都傳遞進(jìn)去,也不需要在全局路由守衛(wèi)里做權(quán)限判斷了。

缺點(diǎn)

  • 需要做頁面跳轉(zhuǎn),不是純粹的單頁應(yīng)用
  • 菜單信息寫死在前端,要改個顯示文字或權(quán)限信息,需要重新編譯
  • 菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標(biāo)題,圖標(biāo)之類的信息,而且路由不一定作為菜單顯示,還要多加字段進(jìn)行標(biāo)識

使用addRoutes動態(tài)掛載路由

addRoutes允許在應(yīng)用初始化之后,動態(tài)的掛載路由。有了這個新姿勢,就不用像前一種方式那樣要在應(yīng)用初始化之要對路由進(jìn)行篩選。

實(shí)現(xiàn)

應(yīng)用初始化的時候先掛載不需要權(quán)限控制的路由,比如登錄頁,404等錯誤頁。

有個問題,addRoutes應(yīng)該何時調(diào)用,在哪里調(diào)用

登錄后,獲取用戶的權(quán)限信息,然后篩選有權(quán)限訪問的路由,再調(diào)用addRoutes添加路由。這個方法是可行的。但是不可能每次進(jìn)入應(yīng)用都需要登錄,用戶刷新瀏覽器又要登陸一次。

所以addRoutes還是要在全局路由守衛(wèi)里進(jìn)行調(diào)用

import router from './router'import store from './store'import { Message } from 'element-ui'import NProgress from 'nprogress' // progress barimport 'nprogress/nprogress.css'// progress bar styleimport { getToken } from '@/utils/auth' // getToken from cookieNProgress.configure({ showSpinner: false })// NProgress Configuration// permission judge functionfunction 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 whitelistrouter.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) { // 判斷當(dāng)前用戶是否已拉取完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) { // 在免登錄白名單,直接進(jìn)入 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) { // 判斷當(dāng)前用戶是否已拉取完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的實(shí)現(xiàn)

缺點(diǎn)

  • 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
  • 菜單信息寫死在前端,要改個顯示文字或權(quán)限信息,需要重新編譯
  • 菜單跟路由耦合在一起,定義路由的時候還有添加菜單顯示標(biāo)題,圖標(biāo)之類的信息,而且路由不一定作為菜單顯示,還要多加字段進(jìn)行標(biāo)識

菜單與路由分離,菜單由后端返回

菜單的顯示標(biāo)題,圖片等需要隨時更改,要對菜單做管理功能。

后端直接根據(jù)用戶權(quán)限返回可訪問的菜單。

實(shí)現(xiàn)

前端定義路由信息(標(biāo)準(zhǔn)的路由定義,不需要加其他標(biāo)記字段)。

{ name: "login", path: "/login", component: () => import("@/pages/Login.vue")}

name字段都不為空,需要根據(jù)此字段與后端返回菜單做關(guān)聯(lián)。

做菜單管理功能的時候,一定要有個字段與前端的路由的name字段對應(yīng)上(也可以是其他字段,只要菜單能找到對應(yīng)的路由或者路由能找到對應(yīng)的菜單就行),并且做唯一性校驗(yàn)。菜單上還需要定義權(quán)限字段,可以是一個或多個。其他信息,比如顯示標(biāo)題,圖標(biāo),排序,鎖定之類的,可以根據(jù)實(shí)際需求進(jìn)行設(shè)計(jì)。

還是在全局路由守衛(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)限更新完成,重新進(jìn)一次當(dāng)前路由 } }  catch (e) { if (whiteList.indexOf(to.path) !== -1) { // 在免登錄白名單,直接進(jìn)入  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) { // 在免登錄白名單,直接進(jìn)入 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的實(shí)現(xiàn)。因?yàn)闆]有使用addRoutes,每次路由跳轉(zhuǎn)的時候都要判斷權(quán)限,這里的判斷也很簡單,因?yàn)椴藛蔚膎ame與路由的name是一一對應(yīng)的,而后端返回的菜單就已經(jīng)是經(jīng)過權(quán)限過濾的,所以如果根據(jù)路由name找不到對應(yīng)的菜單,就表示用戶有沒權(quán)限訪問。

如果路由很多,可以在應(yīng)用初始化的時候,只掛載不需要權(quán)限控制的路由。取得后端返回的菜單后,根據(jù)菜單與路由的對應(yīng)關(guān)系,篩選出可訪問的路由,通過addRoutes動態(tài)掛載。

缺點(diǎn)

  • 菜單需要與路由做一一對應(yīng),前端添加了新功能,需要通過菜單管理功能添加新的菜單,如果菜單配置的不對會導(dǎo)致應(yīng)用不能正常使用
  • 全局路由守衛(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進(jìn)行編譯打包

實(shí)現(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字段換為真正的組件。

至于菜單與路由是否還要分離,怎么對應(yīng),可以根據(jù)實(shí)際需求進(jìn)行處理。

如果有嵌套路由,后端功能設(shè)計(jì)的時候,要注意添加相應(yīng)的字段。前端拿到數(shù)據(jù)也要做相應(yīng)的處理。

缺點(diǎn)

  • 全局路由守衛(wèi)里,每次路由跳轉(zhuǎn)都要做判斷
  • 前后端的配合要求更高

不使用全局路由守衛(wèi)

前面幾種方式,除了登錄頁與主應(yīng)用分離,每次路由跳轉(zhuǎn),都在全局路由守衛(wèi)里做了判斷。

實(shí)現(xiàn)

應(yīng)用初始化的時候只掛載不需要權(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;  }  }); }

因?yàn)楫?dāng)前沒有/路由,會跳到/404

<template> <h1>404</h1></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)登錄,接著判斷應(yī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組件里判斷應(yīng)用是否已經(jīng)初始化(避免初始化后,直接從地址欄輸入地址再次進(jìn)入當(dāng)前組件)。

如果已經(jīng)初始化,跳轉(zhuǎn)/路由(如果后端返回的路由里沒有定義次路由,則會跳轉(zhuǎn)404)。

沒有初始化,則調(diào)用遠(yuǎn)程接口獲取菜單和路由等,然后處理后端返回的路由,將component賦值為真正
的組件,接著調(diào)用addRoutes掛載新路由,最后跳轉(zhuǎn)/路由即可。菜單的處理也是在此處,看實(shí)際
需求。

實(shí)現(xiàn)例子

缺點(diǎn)

  • 在404頁面做了判斷,感覺比較怪異
  • 多引入了一個init頁面組件

總結(jié)

比較推薦后面兩種實(shí)現(xiàn)方式。

好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對武林網(wǎng)的支持。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 无为县| 厦门市| 禄劝| 湛江市| 姚安县| 壤塘县| 天长市| 呈贡县| 英吉沙县| 安康市| 突泉县| 济源市| 荃湾区| 麻江县| 清水河县| 布尔津县| 香港| 宁陵县| 九江市| 巍山| 湘西| 芦山县| 吕梁市| 怀远县| 双柏县| 富民县| 姚安县| 黄陵县| 黄大仙区| 宜兰县| 武胜县| 江口县| 黎平县| 方山县| 陇西县| 武鸣县| 勐海县| 昌宁县| 石首市| 西林县| 商河县|