基于角色+权限配置模式
可以将权限粒度设置的更细致一些。
具体参考
- 前端:登录成功后,再获取权限列表,在页面上进行权限判断。
- 后端:不变
登录
当用户登录时,将用户角色写入到vuex,保存当前用户角色信息。
- vuex中
import {createStore} from 'vuex'
export default createStore({
state: {
token: localStorage.getItem('token') || '',
role: localStorage.getItem('role') || '',
permission: localStorage.getItem('permission') || ''
},
getters: {},
mutations: {
login(state, {token, role, permission}) {
state.token = token
state.role = role
state.permission = permission
localStorage.setItem('token', token)
localStorage.setItem('role', role)
localStorage.setItem('permission', permission)
}
},
actions: {},
modules: {}
})
- 登陆方法
const handleFinish = () => {
const login_info = {
token: '123',
role: formState.role,
permission: {
'admin': {
'department-list': ['get', 'post'],
'department-detail': ['get', 'delete', 'put', 'patch']
},
'user': {
'department-list': ['get'],
'department-detail': ['get']
}
}
}
store.commit('login', login_info)
message.info(formState.user + "登陆成功")
router.replace({name: "admin"})
};
定义路由(不变)
定义路由时,基于 meta 来指定哪些角色的用户可以访问此路由。
路由导航守卫(不变)
用户访问页面时,在导航守卫中,进行判断,是否有权访问此路由。
- 有权,继续访问
- 无权,跳转登录页面
2.4 菜单的加载(不变)
根据vuex中的角色,加载自己的路由,并添加在菜单中。
2.5 按钮控制&权限判断
<template>
<h1>用户管理</h1>
<div>
<ul>
<li v-if='hasPermission("user", "get")'>查看</li>
<li v-if='hasPermission("user", "post")'>新增</li>
<li v-if='hasPermission("user", "put")'>修改</li>
<li v-if='hasPermission("user", "delete")'>删除</li>
<li v-permission="['user','post']">休息休息</li>
</ul>
</div>
</template>
<script setup>
import {hasPermission} from "@/store/permission";
</script>
<style scoped>
</style>
-
directives/permission.js
import store from "@/store"; export default { mounted(el, bindings) { let [name, method] = bindings.value; //console.log(name, method); let totalPermission = store.getters.totalPermission; if(!totalPermission[name]){ el.parentNode && el.parentNode.removeChild(el); } if(totalPermission[name].indexOf(method) === -1){ el.parentNode && el.parentNode.removeChild(el); } } }
-
directives/index.js
import permission from "./permission" //批量注册指令(现在就一个permission) const directives = { permission } //注册的一般写法,循环遍历directives,通过vue.directive注册 export default { install(Vue) { Object.keys(directives).forEach(key => { Vue.directive(key, directives[key]) }) } }
-
main.js
import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import directives from "@/directives"; createApp(App).use(store).use(router).use(directives).mount('#app')
-
store/permisson.js
import store from "@/store"; export function hasPermission(name,method) { console.log(store.getters.totalPermission); console.log(name,method); let totalPermission = store.getters.totalPermission; if(!totalPermission[name]){ return false; } if(totalPermission[name].indexOf(method) !== -1){ return true; } return false; }