The background uses the Ruoyi system, and recently needs to control the menu and button permissions through the background; make a shallow record.
First, set the button permission character and other information in the background system
Create folder store->permission.ts
Persistently store the permission information returned by the backend, here only focus on permissions
import { defineStore } from 'pinia'
export const permissionStore = defineStore('permission', {
state: (): {
userState: {
roles: []
permissions: []
tokenKey: ''
user: {}
}
} => {
return {
userState: {
roles: [],
permissions: [],
tokenKey: '',
user: {}
}
}
},
actions: {
setInfo(info: { permissions: []; roles: []; tokenKey: ''; user: {} }) {
this.userState.permissions = info.permissions
this.userState.roles = info.roles
this.userState.tokenKey = info.tokenKey
this.userState.user = info.user
},
getPermissions() {
return this.userState.permissions
}
},
persist: true
})
After logging in, get the login information, including roles, permission characters, etc.
//获取信息
getInfo().then((res) => {
const _permissionStore = permissionStore()
_permissionStore.setInfo({
permissions: res.permissions,
roles: res.roles,
tokenKey: res.tokenKey,
user: res.user
})
})
main.ts custom directive, for the convenience of global use
app.directive('permission', (el, binding, vnode) => {
const store = permissionStore()
// console.log('权限', store.getPermissions())
const { value } = binding
const all_permission = '*:*:*'
const permissions = store.getPermissions()
if (value && value instanceof Array && value.length > 0) {
const permissionFlag = value
const hasPermissions = permissions.some((permission) => {
return all_permission === permission || permissionFlag.includes(permission)
})
if (!hasPermissions) {
el.parentNode && el.parentNode.removeChild(el)
}
} else {
throw new Error(`请设置操作权限标签值`)
}
})
use
v-permission="['system:user:add']"
Where system:user:add is the permission character set in the menu management
<el-col :span="1.5">
<el-button
class="add_btn"
type="primary"
v-permission="['system:user:add']"
@click="createFrom"
>新增</el-button
>
</el-col>