怎么寫一個有權(quán)限的后臺管理系統(tǒng)

已完成功能:

  • 登錄,超過時間退出登錄
  • 不同賬號不同權(quán)限
  • 在未登錄的時候,手動輸入url返回登錄頁
  • 登錄后,手動輸入非路由內(nèi)的url返回404頁
  • 退出登錄

登錄

  1. 點擊登錄按鈕的時候,調(diào)用vuex里面action的登錄方法,返回token,將token存入state里面,并且存放sessionStorage,以防刷新后vuex的數(shù)據(jù)丟失,同時設(shè)置axios的封裝方法里面的header請求頭的token
// vuex里面
Login({ commit }, userInfo) {
  userInfo.username = userInfo.username.trim();
  console.log(userInfo)
  return new Promise((resolve, reject) => {
    loginFun( userInfo ).then((response: any) => {
      const token = response.data.token;
      // 存儲token
      setCookie('token', token, 1);
      // 修改state里面token
      commit('SET_TOKEN', token);
      resolve();
    }).catch((error: any) => {
      reject(error)
    })
  })
},

權(quán)限

  1. 使用vue-router的全局鉤子router.beforeEach在main.js里面做統(tǒng)一操作,先判斷是否有token,如果沒有直接返回登錄頁,如果有執(zhí)行以下步驟;判斷是否獲取用戶權(quán)限列表,如果沒獲取,則調(diào)用獲取接口
// main.js
router.beforeEach((to: any, from: any, next) => {
  console.log('main to: ', to.path);
  if(store.state.token) {
    if(to.path == '/login'){
      next({path: '/'});
    } else {
      if(store.getters.GetRoles.length == 0){
      //   // 調(diào)用獲取權(quán)限的接口
        RolusFun(store.state.token).then((response: any) => {
          // console.log('獲取的角色數(shù)據(jù):', response);
          const roles = response.data;
          // 將獲取成功的用戶角色傳到vuex里面,以供生成側(cè)邊欄
          store.dispatch('HandleRoute', roles).then(() => {
            router.addRoutes(store.state.asynaRoles) // 動態(tài)添加可訪問路由表
            next({ ...to, replace: true }) // 有問題 
            
          })
        }).catch((error: any) => {
          Message({
            message: '獲取失敗',
            type: "error"
          });
        })
      } else {
        next(); 
      }
    }
  } else {
    // 這里需要注意的時候,next('/login')重置到登錄頁面,會重新調(diào)用router.beforeEach,如果不加個判斷,會造成死循環(huán)
   if (to.path === '/login') { //這就是跳出循環(huán)的關(guān)鍵
      next()
   } else {
       next('/login')
   }
  }
})
  1. 與路由數(shù)組里的權(quán)限相比較,選出可訪問的路由(這里的缺點: 不可隨意修改權(quán)限,否則需要手動修改vue-router里面的權(quán)限列表)
// vuex action
HandleRoute({ commit }, data) { // 處理路由
  return new Promise((resolve, reject) => {
    const roles = data;
    console.log('vuex里面獲取route: ', asyncRoutes);
    const accessedRouters = asyncRoutes.filter( item => { // 過濾出可訪問的路由
      if(item.meta && item.meta.noShow) return item; // 保留404頁面
      if(hasPremission(roles, item)){ // 如果有權(quán)限,開始匹配相應(yīng)的路由
        if(item.children && item.children.length > 0) { //如果路由有子級
          item.children = item.children.filter(child => {
            if(hasPremission(roles, child)) {
              return child;
            }
            return false;
          })
          return item; 
        } else {
          return item;
        }
      }
      return false;
    })
    commit('SET_ROLES', accessedRouters); // 用來渲染側(cè)邊欄
    resolve();
  })
}
  1. vue-router里面配置通用路由和權(quán)限路由,在router.beforeEach里面利用router.addRoutes掛載權(quán)限路由
// route.js
import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

export const commonRoutes = [
  {
    path: '/login',
    name: 'login',
    meta: {title: '登錄', noShow: true},
    component: () => import('@/views/login.vue')
  },
  {
    path: '/',
    name: 'home',
    redirect: '/article',
    component: Home,
    children: [
      {
        path: '/article',
        name: 'article',
        meta: {title: '文章'},
        component: () => import('@/views/article.vue')
      },
      {
        path: '/content',
        name: 'content',
        meta: { title: '內(nèi)容'},
        component: () => import('@/views/content.vue')
      },
    ]
  }
]

export const asyncRoutes = [
  {
    path: '/',
    component: Home,
    redirect: '/article',
    meta: { roles: ['superAdmin', 'admin'] },
    children: [
      {
        path: '/project',
        name: 'project',
        meta: { roles: ['superAdmin', 'admin'], title: '項目'},
        component: () => import('@/views/project.vue')
      }
    ]
  },
  {
    path: '/',
    component: Home,
    redirect: '/article',
    meta: { roles: ['superAdmin'] },
    children: [
      {
        path: '/authority',
        name: 'authority',
        meta: { roles: ['superAdmin'], title: '權(quán)限頁面' },
        component: () => import('@/views/authority.vue')
      },
    ]
  },
  {
    path: '/',
    component: Home,
    redirect: '/article',
    meta: { roles: ['onlyJing'] },
    children: [
      {
        path: '/private',
        name: 'private',
        meta: { roles: ['onlyJing'], title: '個人頁面' },
        component: () => import('@/views/private.vue')
      },
    ]
  },
  {
    path: '*',
    name: 'Error',
    meta: {title: '404', noShow: true},
    component: () => import('@/views/Error.vue')
  }
  
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: commonRoutes
})

export default router
遇到的坑
1. 怎么顯示高亮?

在實現(xiàn)導(dǎo)航高亮的時候,因為使用element中的導(dǎo)航欄,用到了el-menuel-menu-item,這里面只要el-menu中的default-active和el-menu-item中的index保持一致,就可以高亮當(dāng)前點擊的導(dǎo)航,index表示唯一標(biāo)志,default-active表示當(dāng)前激活菜單的index,兩者皆為string類型。所以這里的index我們可以設(shè)為當(dāng)前循環(huán)的路由item.path,而default-active為當(dāng)前url里面的路由(使用this.route.path來獲取。注意:不是this.router.path哦~), 同時需要在el-menu里面設(shè)置router,router: 是否使用 vue-router 的模式,啟用該模式會在激活導(dǎo)航時以 index 作為 path 進(jìn)行路由跳轉(zhuǎn)

<el-menu 
     :default-active="this.$route.path"
     router
     background-color="#545c64"
     text-color="#fff"
     active-text-color="#ffd04b">
      <el-menu-item v-for="(item, index) in rolesList"
        :key="index"
        :index="item.path">{{ item.meta.title }}</el-menu-item>
    </el-menu>
2. 后臺管理系統(tǒng)為什么登陸后刷新還回到登錄頁以及怎么解決?

因為登錄后的token存在vuex里面,而vuex刷新后數(shù)據(jù)為空,所以在登錄請求后,將token存到瀏覽緩存中,并且在vuex里面state中token的值直接在瀏覽器緩存中獲取,這樣每次刷新,token都是有值的,直接走登錄后里面的邏輯。

3. 如何做到登錄后每次刷新都是在當(dāng)前路由?

next({ ...to, replace: true }), 一般在router.beforeEach里面動態(tài)掛載路由后,使用這個,之所以不使用next()是因為,router.addRoute從解析到掛載到路由,可能會慢于next()的執(zhí)行,從而next()執(zhí)行中找不到下一個路由的路徑,同時,不使用next('/path')具體跳轉(zhuǎn)到某個路由,就是為了解決每次刷新都是在當(dāng)前路由的問題,...to是動態(tài)記錄下一個路由的信息。

4. this.router和this.route的區(qū)別

this.router:表示全局路由對象,項目中通過router路由參數(shù)注入路由之后,在任何一個頁面都可以通過此方法取到路由對象,并調(diào)用其push(), go()等方法
</br>
this.route:
表示當(dāng)前正在用于跳轉(zhuǎn)的路由對象,可以調(diào)用其name, path, query, params等方法

5. 寫 next({ ...to, replace: true })報錯 \color{red}{Uncaught (in promise) Error: Redirected when going from "/login" to "/article" via a navigation guard.} 解決方法?

目前想到的辦法就是,將vue-router的版本回退到低一些的版本,比如3.0.7版本,具體原因不詳

6. 如果是http://localhost:8080/#/怎么重定向到默認(rèn)路由頁面?登錄后手動輸入url怎么重定向到404頁面?
  • 在路由里面設(shè)置redirect: '/article',重定向到默認(rèn)頁面
  • 在路由router.js里面,利用通配符,將不匹配的路由全部重定向到404頁面,同時,將404路由在權(quán)限路由中寫,因為要保證該路由要在路由數(shù)組的最后, 同時在action里面篩選動態(tài)路由的時候,主要不要過濾了該路由,由此,這里加了個參數(shù)noShow作為標(biāo)識
{
  path: '*',
  name: 'Error',
  meta: {title: '404', noShow: true},
  component: () => import('@/views/Error.vue')
}
7. 怎么退出登錄
loginOut() {
   delCookie('token'); // 清除cookie
   window.location.reload(); // 刷新頁面
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容