使用vue開發后台管理系統,除了路由與頁面搭建,最主要的還有登錄權限與路由守衛。因為直接使用的vue-admin-element的后台管理系統,其中已經做了登錄權限的管理,此次記錄是為更好的梳理適合自己項目的流程,以及后續的查看與補充。
vue-admin-element模板地址:https://github.com/PanJiaChen/vue-element-admin
vue-admin-element模板介紹:https://segmentfault.com/a/1190000009275424
關於項目文件目錄
這里首先介紹一下相關文件目錄,方便后續的路徑查看(主要標紅)
├── build // 構建相關 ├── config // 配置相關 ├── src // 源代碼 │ ├── api // 所有請求 │ ├── assets // 主題 字體等靜態資源 │ ├── components // 全局公用組件 │ ├── directive // 全局指令 │ ├── filtres // 全局 filter │ ├── icons // 項目所有 svg icons │ ├── lang // 國際化 language │ ├── mock // 項目mock 模擬數據 │ ├── router // 路由 │ ├── store // 全局 store管理 │ ├── styles // 全局樣式 │ ├── utils // 全局公用方法 │ ├── vendor // 公用vendor │ ├── views // view頁面 │ ├── App.vue // 入口頁面 │ ├── main.js // 入口 加載組件 初始化等 │ └── permission.js // 權限管理 ├── static // 第三方不打包資源 │ └── Tinymce // 富文本 ├── .babelrc // babel-loader 配置 ├── eslintrc.js // eslint 配置項 ├── .gitignore // git 忽略項 ├── favicon.ico // favicon圖標 ├── index.html // html模板 └── package.json // package.json
1、進入系統后首先就是登錄功能,這里使用了vuex管理登錄信息與用戶信息
頁面路徑:src/views/login/index
//登錄
handleLogin() {
//驗證登錄信息
this.$refs.loginForm.validate(valid => {
if (valid) {
//指向src/store/modules/user.js中的登錄方法Login
this.$store.dispatch('Login', this.loginForm).then(() => {
//通過Login后路由定向到首頁
this.$router.push({ path: '/' })
}).catch(() => {
})
} else {
console.log('error submit!!')
return false
}
})
},
2、管理登錄與獲取用戶信息
頁面路徑:src/store/modules/user.js
// 登錄
Login({ commit }, userInfo) {
const username = userInfo.username.trim() //去空
const fd = new FormData() //登錄參數
fd.append('username', username)
fd.append('password', userInfo.password)
return new Promise((resolve, reject) => {
login(fd).then(response => {
const data = response.data
setToken(data.token) //存儲token信息
commit('SET_TOKEN', data.access_token)
resolve()
}).catch(error => {
// console.log(5)
reject(error)
})
})
},
// 獲取用戶信息
GetInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
const data = response.data
//獲取用戶權限並存儲roles
if (data.roles && data.roles.length > 0) {
commit('SET_ROLES', data.roles)
} else {
reject('getInfo: roles must be a non-null array !')
}
commit('SET_USERNAME', data.username)
commit('SET_NICKNAME', data.nickname)
resolve(response)
}).catch(error => {
reject(error)
})
})
},
3、請求攔截
頁面路徑:src/utils/request.js
import axios from 'axios'
// import qs from "qs"
import { Message } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import { apiURL } from '@/api/config/ip-config'
// 創建axios實例
const service = axios.create({
baseURL: process.env.BASE_API, // api的base_url
timeout: 15000 // 請求超時時間
})
// request攔截器
service.interceptors.request.use(
config => {
if (getToken()) {
// 如果存在token,在每個請求頭中帶上token信息。x-token是自己定義的key,可與后端協商統一
config.headers['X-token'] = getToken()
}
return config
},
error => {
// Do something with request error
// console.log(error) // for debug
Promise.reject(error)
}
)
// respone攔截器
service.interceptors.response.use(
(response) => {
/**
*自定義code來標示請求狀態
* 當code返回如下情況則說明權限有問題,登出並返回到登錄頁
* 如想通過xmlhttprequest狀態碼來標識,邏輯可寫在下面error中
*/
const res = response.data
if (res.code) {
// 自定義狀態碼1000為有效,其他值為特殊狀態,可結合自己業務進行修改
if (res.code !== 1000) {
Message({
message: res.message,
type: 'error',
duration: 5 * 1000
})
// 50008:非法的token; 50012:其他客戶端登錄了; 50014:Token 過期了;
// if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// MessageBox.confirm(
// '你已被登出,可以取消繼續留在該頁面,或者重新登錄',
// '確定登出',
// {
// confirmButtonText: '重新登錄',
// cancelButtonText: '取消',
// type: 'warning'
// }
// ).then(() => {
// store.dispatch('FedLogOut').then(() => {
// location.reload() // 為了重新實例化vue-router對象 避免bug
// })
// })
// }
return Promise.reject('error')
} else {
return response.data
}
} else {
return response
}
// return response
},
error => {
if (typeof (error.response) !== 'undefined') {
if (error.response.status === 401) {
// MessageBox.alert(error.response.data.message, '提示', {
// confirmButtonText: '重新登錄',
// type: 'warning'
// })
Message({
message: error.response.data.message,
type: 'info',
duration: 5 * 1000
})
setTimeout(function() {
store.dispatch('FedLogOut').then(() => {
location.reload()// 為了重新實例化vue-router對象 避免bug
})
}, 1000)
// .then(() => {
// })
} else {
Message({
message: error.response.data.message,
type: 'error',
duration: 5 * 1000
})
}
} else {
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
}
return Promise.reject(error)
}
)
export default service
4、設置路由
頁面路徑:src/router/index.js
import Vue from 'vue' import Router from 'vue-router' // in development-env not use lazy-loading, because lazy-loading too many pages will cause webpack hot update too slow. so only in production use lazy-loading; // detail: https://panjiachen.github.io/vue-element-admin-site/#/lazy-loading Vue.use(Router) /* Layout */ import Layout from '../views/layout/Layout' /** * hidden: true if `hidden:true` will not show in the sidebar(default is false) * alwaysShow: true if set true, will always show the root menu, whatever its child routes length * if not set alwaysShow, only more than one route under the children * it will becomes nested mode, otherwise not show the root menu * redirect: noredirect if `redirect:noredirect` will no redirct in the breadcrumb * name:'router-name' the name is used by <keep-alive> (must set!!!) * meta : { title: 'title' the name show in submenu and breadcrumb (recommend set) icon: 'svg-name' the icon show in the sidebar, } **/ export const constantRouterMap = [ // 基礎-路由設置 { path: '/login', component: () => import('@/views/login/index'), hidden: true }, { path: '/404', component: () => import('@/views/404'), hidden: true }, // { path: '*', redirect: '/404', hidden: true }, { path: '', component: Layout, redirect: 'home', children: [{ path: 'home', component: () => import('@/views/home/index'), name: 'home', meta: { title: '首頁', icon: 'table', noCache: true } }] } ] export const asyncRouterMap = [
{
path: '/demo',
component: Layout,
redirect: '/demo/demoChild1',
alwaysShow: true, // will always show the root menu
name: 'Demo',
meta: {
title: '示例',
icon: 'tree',
roles: ['admin','demoRoles']
},
children: [
{
path: 'demoChild1',
component: () => import('@/views/demo/demoChild1'),
name: 'DemoChild1',
meta: {
title: '示例C1'
}
},
{
path: 'demoChild2',
component: () => import('@/views/demo/demoChild2'),
name: 'DemoChild2',
meta: {
title: '示例C2'
}
}
]
},
{ path: '*', redirect: '/404', hidden: true } // 很重要,如果動態路由,一定要將404頁面定義在最后,防止無法匹配頁面報錯
]
//重置路由
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: constantRouterMap.concat(asyncRouterMap)
// routes: []
})
const router = createRouter()
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default router
5、過濾路由
如果菜單欄都是前端寫死的那就不用考慮這一步。
但我們在做后台管理系統的時候,通常是根據登錄用戶所擁有的權限來展示不同的菜單欄。
所以匹配合適的路由就尤為重要。
頁面路徑:src/store/permission.js
import { asyncRouterMap, constantRouterMap } from '@/router'
/**
* 引入 src/router/index中定義的asyncRouterMap與constantRouterMap
* constantRounterMap:一般寫入基礎路由/login、/404等
* asyncRouterMap:寫入需配置路由,且由roles管理
/**
* 通過meta.role判斷是否與當前用戶權限匹配
* @param roles
* @param route
*/
function hasPermission(roles, route) {
if (route.meta && route.meta.roles) {
return roles.some(role => route.meta.roles.indexOf(role) >= 0)
} else {
return true
}
}
/**
* 遞歸過濾異步路由表,返回符合用戶角色權限的路由表
* @param asyncRouterMap
* @param roles
*/
function filterAsyncRouter(asyncRouterMap, roles) {
const accessedRouters = asyncRouterMap.filter(route => {
if (hasPermission(roles, route)) {
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children, roles)
}
return true
}
return false
})
return accessedRouters
}
const permission = {
state: {
routers: constantRouterMap,
addRouters: []
},
mutations: {
SET_ROUTERS: (state, routers) => {
state.addRouters = routers
state.routers = constantRouterMap.concat(routers)
}
},
actions: {
GenerateRoutes({ commit }, data) {
return new Promise(resolve => {
const { roles } = data
let accessedRouters = []
// 此處可根據業務需求做調整,本項目是admin擁有所有權限
if (roles.indexOf('admin') >= 0) {
accessedRouters = asyncRouterMap
} else {
accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
}
commit('SET_ROUTERS', accessedRouters)
resolve()
})
}
}
}
export default permission
6、路由攔截與路由守衛
在我們拿到用戶roles后,通過router.addRoutes
動態掛載路由
頁面路徑:src/permission.js
import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 進度條
import 'nprogress/nprogress.css'// Progress 進度條樣式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 驗權
// 過濾符合條件的路由-可根據自己業務做調整-根據參數 to 做信息判定,如果符合條件,則前往相應頁面,否則前往404
function hasPermission(roles, to) {
if (roles.indexOf('admin') >= 0) {
return true // admin permission passed directly
}
if (to.meta.roles) {
return roles.some(role => to.meta.roles.indexOf(role) >= 0)
} else {
return true
}
}
const whiteList = ['/login', '/404'] // 不重定向白名單
router.beforeEach((to, from, next) => {
NProgress.start()
if (getToken()) {
// 路由守衛
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) {
// 如果權限roles為空,則重新獲取用戶信息,更新roles
store.dispatch('GetInfo').then(res => { // 拉取用戶信息
const roles = res.data.roles
store.dispatch('GenerateRoutes', { roles }).then(() => { // 根據roles權限生成可訪問的路由表
router.addRoutes(store.getters.addRouters) // 動態添加可訪問路由表
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 {
// 如果已存在權限,過濾符合條件的路由,如果不符合,則跳往404頁面
// 此處hasPermission是驗證roles是否符合,其中參數to是要跳往的頁面路由相關信息,可根據自己業務修改
if (hasPermission(store.getters.roles, to)) {
next()//
} else {
next({ path: '/404', replace: true, query: { noGoBack: true }})
}
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next('/login')
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done() // 結束Progress
})
至此,關於vue-admin的登錄與權限基本就這些,當然還有很多其他的方法,這只是當前項目所需,后續有完善再不斷補充。
關於vue-admin-element的更多信息可以參考這里:vue-admin-element模板介紹:https://segmentfault.com/a/1190000009275424。