本篇內容較長,先看下效果:
javascript
{
"code": 200,
"msg": "",
"data": {
"id": "1",
"username": "admin",
"roles": [
{
"id": 1,
"describe": null,
"rolename": "ROLE_ADMIN",
"permissions": null
}
],
"menus": [
{
"per_id": 1101,
"per_paerent_id": 0,
"per_name": "權限管理",
"per_resource": "auth",
"children": [
{
"per_id": 1102,
"per_paerent_id": 1101,
"per_name": "角色管理",
"per_resource": "role",
"children": null
},
{
"per_id": 1103,
"per_paerent_id": 1101,
"per_name": "資源管理",
"per_resource": "per",
"children": null
}
]
}
]
}
}
複製代碼
因爲本人是個後端小辣雞,前端對我來講簡直就是地獄…就使用了GitHub
上的輪子試着改了一下。感謝@PanJiaChen 的項目,我就使用了其中的模板來作的,若是有什麼不完美的但願指出。css
在先後端分離項目中咱們前端只須要對數據進行渲染就ok了。目先後端已經能夠成功給咱們返回了用戶信息,前端實現權限體系的主要思路是html
首先修改login接口:src\api\login.js
修改成Spring Boot的接口。前端
import request from '@/utils/request'
/**
* 登陸操做
* @param {用戶名} username
* @param {密碼} password
*/
export function login(username, password) {
return request({
url: '/auth/login',
method: 'post',
data: {
username,
password
}
})
}
/**
* 獲取用戶信息
* @param {token} token
*/
export function getInfo(token) {
return request({
url: '/getUserInfo',
method: 'get',
params: { token }
})
}
export function logout() {
return request({
url: 'user/logout',
method: 'post'
})
}
複製代碼
修改dev.env.js
爲本地接口vue
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
BASE_API: '"http://localhost:8086"',
})
複製代碼
修改axios
配置文件java
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
// 建立axios實例
const service = axios.create({
baseURL: process.env.BASE_API, // api 的 base_url
timeout: 5000 // 請求超時時間
})
// request攔截器
service.interceptors.request.use(
config => {
if (store.getters.token) {
// 這裏修改成'jwtHeader'
config.headers['jwtHeader'] = getToken() // 讓每一個請求攜帶自定義token 請根據實際狀況自行修改
}
return config
},
error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
}
)
// response 攔截器
service.interceptors.response.use(
response => {
/**
* code爲非200是拋錯 可結合本身業務進行修改
*/
const res = response.data
if (res.code !== 200) {
Message({
message: res.message,
type: 'error',
duration: 5 * 1000
})
// 50008:非法的token; 50012:其餘客戶端登陸了; 50014:Token 過時了;
if (res.code === 500 || res.code === 500 || res.code === 500) {
MessageBox.confirm(
'你已被登出,能夠取消繼續留在該頁面,或者從新登陸',
'肯定登出',
{
confirmButtonText: '從新登陸',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('FedLogOut').then(() => {
location.reload() // 爲了從新實例化vue-router對象 避免bug
})
})
}
return Promise.reject('error')
} else {
return response.data
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
複製代碼
以上都是最基本的鏈接配置。webpack
src\router\index.jsios
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 redirect 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
breadcrumb: false if false, the item will hidden in breadcrumb(default is true)
}
**/
// 全部權限通用路由表
// 這裏就是一些公共界面如,錯誤提示頁面,登陸頁面是不須要權限的就能夠在這個裏面配置
export const constantRouterMap = [
{
path: '/login',
name: 'Login',
component: () =>
import('@/views/login/index'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
name: 'Dashboard',
hidden: true,
children: [{
path: 'dashboard',
component: () =>
import('@/views/dashboard/index')
}, {
path: 'userinfo',
name: 'UserInfo',
component: () =>
import('@/views/dashboard/userinfo')
}]
},
{
path: '*',
redirect: '/404',
hidden: true
}
]
export default new Router({
// mode: 'history', //後端支持可開
scrollBehavior: () => ({ y: 0 }),
routes: constantRouterMap
})
// 異步掛載的路由
// 動態須要根據權限加載的路由表(這裏的路由時用來動態加載的,通俗點講就是須要權限控制的路由都在這個裏面配置)
export const asyncRouterMap = [
{
path: '/auth',
component: Layout,
name: 'auth',
meta: {
resources: 'auth',
title: '權限管理'
},
children: [
{
path: 'per',
component: () => import('@/views/pre/perm/index'),
name: 'per',
meta: {
resources: 'per'
}
},
{
path: 'user',
component: () => import('@/views/pre/user/index'),
name: 'user',
meta: {
resources: 'user'
}
},
{
path: 'role',
component: () => import('@/views/pre/role/index'),
name: 'role',
meta: {
resources: 'role'
}
}
]
}
]
複製代碼
而後你須要根據import
的指令去添加相應的Vue
文件。git
其實也就是拿着後臺獲取到的路由,而後和上面配置的路由進行判斷,若是符合就加到用戶的真實路由中。
一、首先修改src\store\modules\user.jsgithub
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
const user = {
state: {
token: getToken(),
username: '',
user: {},
roles: [], // 用戶角色列表
menus: [] // 菜單列表
},
mutations: {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_INFO: (state, user) => {
state.username = user.username
state.user = user
},
SET_MENUS: (state, menus) => {
state.menus = menus
},
SET_ROLES: (state, roles) => {
state.roles = roles
}
},
actions: {
// 登陸
Login({ commit }, userInfo) {
const username = userInfo.username.trim()
return new Promise((resolve, reject) => {
login(username, userInfo.password).then(res => {
const data = res.data
setToken(data)
commit('SET_TOKEN', data)
resolve()
}).catch(error => {
reject(error)
})
})
},
// 獲取用戶信息
GetInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
const data = response.data
if (data.roles && data.roles.length > 0) { // 驗證返回的roles是不是一個非空數組
commit('SET_ROLES', data.roles)
} else {
reject('getInfo: roles must be a non-null array !')
}
commit('SET_MENUS', data.menus)
commit('SET_INFO', data)
resolve(response)
}).catch(error => {
reject(error)
})
})
},
// 登出
LogOut({ commit, state }) {
return new Promise((resolve, reject) => {
logout(state.token).then(() => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
commit('SET_INFO', '')
removeToken()
resolve()
}).catch(error => {
reject(error)
})
})
},
// 前端 登出
FedLogOut({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
removeToken()
resolve()
})
}
}
}
export default user
複製代碼
這裏使用了Vuex
進行狀態管理,重點關注下actions
中的Login
和GetInfo
方法,Login
則是登陸以後獲取到token
而後把token
存儲,而後GetInfo
就是拿着token
去請求接口獲取用戶角色、權限資源信息了。
二、這個文件的做用就是處理路由,把從後臺獲取的路由和咱們配置的asyncRouterMap
進行匹配,而後就返回用戶當前真實的路由了…也就是幾個forEach
而後把公共的和當前用戶的路由addRouters
就搞定了。
// store/permission.js
import { asyncRouterMap, constantRouterMap } from '@/router'
/**
*
* @param {Array} userRouter 後臺接口請求的路由
* @param {Array} allRouter 前端配置好的全部動態路由的集合
* @return {Array} userRealRouters 過濾後的路由
*/
export function userCurrentRouter(userRouter = [], allRouter = []) {
var userRealRouters = []
allRouter.forEach((router, index) => {
userRouter.forEach((item, index) => {
// 拿用戶的路由和配置路由進行匹配判斷
if (item.per_resource === router.meta.resources) {
// 對路由下的子路由進行判斷,遞歸添加
if (item.children && item.children.length > 0) {
router.children = userCurrentRouter(item.children, router.children)
}
// 這裏是設置側邊欄的顯示title還能夠顯示圖標(沒作)
router.meta.title = item.per_name
userRealRouters.push(router)
}
})
})
return userRealRouters
}
const permission = {
state: {
routers: constantRouterMap,
apiRouters: [] // 後臺接口獲取獲得的路由(per_resource)
},
mutations: {
SET_ROUTERS: (state, routers) => {
state.apiRouters = routers
state.routers = constantRouterMap.concat(routers)
}
},
actions: {
GenerateRoutes({ commit }, data) {
return new Promise(resolve => {
commit('SET_ROUTERS', userCurrentRouter(data, asyncRouterMap))
resolve()
})
}
}
}
export default permission
複製代碼
重點關注下userCurrentRouter
和GenerateRoutes
,第一個是匹配路由,第二個是把公共的路由和真實路由匹配到一塊兒。最主要的是理解Vuex
的意義。
三、此外修改一下src\store\getters.js文件
const getters = {
sidebar: state => state.app.sidebar,
token: state => state.user.token,
username: state => state.user.username,
roles: state => state.user.roles,
user: state => state.user.user,
menus: state => state.user.menus,
menu: state => state.permission.routers,
apiRouters: state => state.permission.apiRouters
}
export default getters
複製代碼
其實也就是你想要哪些信息,而後在裏面定義好,而後咱們就能夠全局從Vuex
中拿了,是否是很方便!
四、修改src\store\index.js
import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import user from './modules/user'
import permission from './modules/permission'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app,
user,
permission
},
getters
})
export default store
複製代碼
五、而後重要的一步來了,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' // 驗權
const whiteList = ['/login'] // 不重定向白名單
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) { // 判斷當前用戶是否已拉取完user_info信息
store.dispatch('GetInfo').then(res => {
// 生成可訪問的路由表
store.dispatch('GenerateRoutes', store.getters.menus).then(r => {
// 動態添加可訪問路由表
router.addRoutes(store.getters.apiRouters)
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 {
next()
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next(`/login?redirect=${to.path}`) // 不然所有重定向到登陸頁
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done() // 結束Progress
})
複製代碼
這個就是判斷是否正確的拿到路由信息而後會給咱們生成路由。
六、修改src\views\layout\components\Sidebar\index.vue
<template>
<el-scrollbar wrap-class="scrollbar-wrapper">
<el-menu
:show-timeout="200"
:default-active="$route.path"
:collapse="isCollapse"
mode="vertical"
background-color="#304156"
text-color="#bfcbd9"
active-text-color="#409EFF"
>
<sidebar-item v-for="route in menu" :key="route.path" :item="route" :base-path="route.path"/>
</el-menu>
</el-scrollbar>
</template>
<script>
import { mapGetters } from 'vuex'
import SidebarItem from './SidebarItem'
export default {
components: {
SidebarItem
},
computed: {
...mapGetters([
'menu',
'sidebar'
]),
isCollapse() {
return !this.sidebar.opened
}
}
}
</script>
複製代碼
用v-for
指令放到sideBar
中去,目前爲止基本動態的路由菜單已經能夠生成了。若是有什麼問題,請聯繫我指正…感謝…代碼已經同步到GitHub
。
# clone the project
git clone https://github.com/ywbjja/Vue_templete.git
# install dependency
npm install
# develop
npm run dev
複製代碼