1. 程式人生 > 實用技巧 >頁面許可權控制和登陸驗證

頁面許可權控制和登陸驗證

一、頁面許可權控制

1)思路:在每一個路由的meta屬性內,將能訪問該路由的角色配置到roles內,使用者登入的時候,返回使用者的角色,在全域性路由守衛內,把要跳轉的路由的roles和使用者的roles做下比對,,如果使用者的roles包含在路由的roles內,則允許訪問,否則不允許訪問。

// 路由配置
routes: [ { path:
'/login', name: 'login', meta: { roles: ['admin', 'user'] }, component: ()
=> import('../components/Login.vue') }, { path: 'home', name: 'home', meta: { roles: ['admin'] }, component: () => import('../views/Home.vue') }, ]
// 路由守衛

// 獲取到的使用者角色資訊
const userInfoRoles = ''
router.beforeEach((to, from, next) => {
if (to.meta.roles.includes(userInfoRoles)) {
    next()
  }
else {
    next({path:
'/404'})
  }
})

2)思路:動態路由,根據使用者登入後返回的資訊,利用addRoutes新增動態路由,其中404頁面放在路由最後。

const asyncRoutes = {
    'home': {
        path: 'home',
        name: 'home',
        component: () => import('../views/Home.vue')
    },
    
't1': { path: 't1', name: 't1', component: () => import('../views/T1.vue') }, 'password': { path: 'password', name: 'password', component: () => import('../views/Password.vue') }, 'msg': { path: 'msg', name: 'msg', component: () => import('../views/Msg.vue') }, 'userinfo': { path: 'userinfo', name: 'userinfo', component: () => import('../views/UserInfo.vue') } } // 傳入後臺資料 生成路由表 router.addRoutes(menusToRoutes(menusData))
// 將選單資訊轉成對應的路由資訊 動態新增 function menusToRoutes(data) { const result = [] const children = [] result.push({ path: '/', component: () => import('../components/Index.vue'), children, })
  // 根據後臺返回的使用者許可權的欄位,在asyncRoutes內遍歷取到符合要求的路由,新增到result內 /*data.forEach(item
=> { generateRoutes(children, item) })*/ children.push({ path: 'error', name: 'error', component: () => import('../components/Error.vue') }) // 最後新增404頁面 否則會在登陸成功後跳到404頁面 result.push( {path: '*', redirect: '/error'}, ) return result } /*function generateRoutes(children, item) { if (item.name) { children.push(asyncRoutes[item.name]) } else if (item.children) { item.children.forEach(e => { generateRoutes(children, e) }) } }*/


二、登入驗證

思路:頁面只需要登入一次,當第一次登入的時候,通過token或者cookie存入到本地,再次開啟頁面時,在全域性路由守衛中先取token或cookie,沒有的話則跳轉到登入頁

router.beforeEach((to, from, next) => {
    if (localStorage.getItem('token')) {
        if (to.path === '/login') {
      // 已登入 next({path:
'/'}) } else { next({path: to.path || '/'}) } } else { if (to.path === '/login') { next() } else { next(`/login?redirect=${to.path}`) } } })

asyncRoutes