按钮权限
- 通过指令的方式添加:通过指令对应的值从state中获取当前按钮的权限,如果没有权限,就通过父级节点移除当前节点
Vue.directive('has', {
inserted(el, bindings, vnode){
let permissionName = bindings.value;
let r = vnode.context.$store.state.btnPermission[permissionName];
!r && el.parentNode.removeChild(el);
}
})
路由权限
获取有权限的路由
- 接口获取有权限的路由信息authList
- 从全部路由配置authRoutes中过滤有权限的路由列表
import {authRoutes} from './router.js'
export default new Vuex.Store({
state: {
hasPermission: false,
authList: [],
btnPermission: {
edit: true,
add: false
}
},
mutations: {
setPermission(state) {
state.hasPermission = true
},
setAuthList(state, list) {
state.authList = list
}
},
actions: {
async getMenuList({commit}) {
let {data} = await axios.get('http://localhost:3000/category');
let r = data.menuList.map(menu => ({
name: menu.name,
auth: menu.auth
}))
commit('setAuthList', r)
commit('setPermission')
return r
},
async getAuthRoutes({dispatch}) {
let authList = await dispatch('getMenuList');
let auths = authList.map(item => item.auth);
const filter = (authRoutes) => {
let res = authRoutes.filter(route => {
if (auths.includes(route.name)) {
if (route.children) {
route.children = filter(route.children)
}
return route
}
})
return res
}
return filter(authRoutes);
}
}
})
动态添加
- 使用路由钩子beforeEach;addRoutes进行动态添加;动态添加的路由会在下次生效,可以通过next({...to, replace: true})进行模拟跳转,使新增加的路由立即生效,且不会记录历史;原理是history.replaceState
router.beforeEach(async (to, from, next) => {
if(!store.state.hasPermission) {
let needRoutes = await store.dispatch('getAuthRoutes'); // 获取有权限的路由
router.addRoutes(needRoutes);
next({
...to,
replace: true,
});
} else {
next()
}
})
动态添加路由的优点:即使用户知道某页面对应的路径,在地址栏输入路径后,如果没有权限,就不会跳转