頁面權限控制和登陸驗證

一、頁面權限控制

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章