動態(tài)菜單
這幾天在做VUE的動態(tài)菜單及權(quán)限,參考了下:
https://segmentfault.com/a/1190000015419713?utm_source=tag-newest
然后發(fā)現(xiàn)和我的需求還是有點(diǎn)不符:上面的作者是整個權(quán)限都是從接口拉下來的
而我的需求是:原來有一部分權(quán)限,然后從接口獲取另外一部分權(quán)限,PUSH到現(xiàn)有權(quán)限中
所以對作者的GIT代碼進(jìn)行了修改,原來的權(quán)限:
const vueRouter = new Router({
routes: [
{
path: '/',
name: 'login',
component: Login
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '*',
component: error404
},
{
path: '/manage',
name: '首頁',
component: Manage,
meta: { title: '首頁' },
children: [
{
path: 'home',
component: Home,
meta: { title: '首頁' }
}
]
},
{
path: '/404',
name: '出錯了',
component: error404
}
]
//路由樣式
// linkActiveClass: "active-router",
// linkExactActiveClass: "exact-router"
})
主要修改的是permission.js
import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import axios from 'axios'
const _import = require('@/router/_import_' + process.env.NODE_ENV)//獲取組件的方法
import Layout from '@/page/manage' //Layout 是架構(gòu)組件,不在后臺返回,在文件里單獨(dú)引入
import { getToken } from '@/utils/auth' // getToken from cookie
router.beforeEach((to, from, next) => {
console.log("====beforeEach====")
if (getToken()) { //如果用戶已經(jīng)登錄
if (to.path === '/login') {
next()
// NProgress.done() // if current page is dashboard will not trigger afterEach hook, so manually handle it
} else {
if (store.getters.getMenu.length === 0) {
store.dispatch('GetUserInfo').then(res => {
var getRouter = res.data.router//后臺拿到路由
routerGo(to, next, getRouter)//執(zhí)行路由跳轉(zhuǎn)方法
}).catch((err) => {
store.dispatch('FedLogOut').then(() => {
// Message.error(err || 'Verification failed, please login again')
console.log(err)
next({ path: '/login' })
})
})
} else {
next();
}
}
}
} else {
if (to.path == '/login') {//如果是登錄頁面路徑,就直接next()
next();
} else {//不然就跳轉(zhuǎn)到登錄;
next('/login');
}
}
})
function routerGo(to, next, getRouter) {
getRouter = filterAsyncRouter(getRouter) //過濾路由
getRouter.map(v => { router.options.routes.push(v) })//將接口獲取到的路由push到現(xiàn)有路由中
router.addRoutes(getRouter)//動態(tài)添加路由
global.antRouter = router.options.routes //將路由數(shù)據(jù)傳遞給全局變量,做側(cè)邊欄菜單渲染工作
next({ ...to, replace: true }) // hack方法 確保addRoutes已完成 ,set the replace:
}
function filterAsyncRouter(asyncRouterMap = []) { //遍歷后臺傳來的路由字符串,轉(zhuǎn)換為組件對象
const accessedRouters = asyncRouterMap.filter(route => {
if (route.component) {
if (route.component === 'Layout') {//Layout組件特殊處理
route.component = Layout
} else {
route.component = _import(route.component)
}
}
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children)
}
return true
})
return accessedRouters
}
關(guān)鍵是這句getRouter.map(v => { router.options.routes.push(v) })//將接口獲取到的路由push到現(xiàn)有路由中
如果你想加入到現(xiàn)有router的某個節(jié)點(diǎn)的children里 可以這樣:
router.options.routes[0].children.push()
這里還要注意的是 beforeEach會出現(xiàn)死循環(huán)
因為next({ path: '/login' })next方法加了參數(shù) 就又會走一次beforeEach方法 如果是next()就不會
可以這樣處理:
if (to.path == '/login') {//如果是登錄頁面路徑,就直接next()
next();
} else {//不然就跳轉(zhuǎn)到登錄;
next('/login');
}
視圖權(quán)限
也就是按鈕級別的權(quán)限。原理很簡單,利用router的meta字段
{
"path": "/system",
"component": "Layout",
"redirect": "/system/userList",
"name": "系統(tǒng)管理",
"meta": {
"title": "系統(tǒng)管理",
"icon": "el-icon-setting"
},
"children": [{
"path": "userList",
"name": "用戶列表",
"component": "user/index",
"meta": {
"title": "用戶列表",
"icon": "el-icon-tickets",
"permission": ['add'] //按鈕權(quán)限
}
}
]
}
meta.permission字段里放入的是該用戶在此頁面能操作的按鈕權(quán)限的標(biāo)識,比如這個頁面有add、edit、delele權(quán)限,但是你只想讓這個用戶使用add,那么就"permission": ['add']
接著自定義指令btnPermission.js,在mian.js導(dǎo)入
import Vue from 'vue'
/**權(quán)限指令**/
Vue.directive('has', {
inserted: function (el, binding, vnode) {
let permissionList = vnode.context.$route.meta.permission;
if (!permissionList || !permissionList.includes(binding.value.role)) {
el.parentNode.removeChild(el)
}
}
})
export { has }
如何使用:
<el-button type="success" icon="el-icon-circle-plus-outline" @click="handeleAdd" v-has="{role : 'add'}">添加</el-button>
這里要注意vue2.0 自定義指令 v-has="{role : 'add'}"參數(shù)必須要傳入對象 否則會無效
具體代碼我上傳到了GIT:https://github.com/yoolika/admin-manage