我有一个组件,如果用户有权限,我想显示它,但 Can 组件似乎隐藏了该组件,而不管用户权限如何。
以下是我的ability.js 模块
import {Ability, AbilityBuilder} from "@casl/ability";
export default function defineAbilityFor(hasRole) {
const { can, cannot, build } = new AbilityBuilder(Ability)
if (hasRole !== undefined) {
console.log(hasRole)
can('manage', 'all')
can('create', 'all')
} else {
can('read', 'all')
cannot('create', 'all')
}
return build()
}
我将城堡添加为我的 main.js,如下所示:
const app = createApp(App)
app.use(router)
app.use(store)
app.use(abilitiesPlugin, ability(), {
useGlobalProperties: true
})
app.component(Can.name, Can)
app.mount('#app')
以下是我需要进行权限检查的组件。
<template>
<div class="d-flex flex-column px-4">
<div class="d-flex justify-content-end">
<Can I="create" an="Institution">
<button class="btn btn-sm btn-outline-success" @click="addInst = true">{{ action }}</button>
</Can>
</div>
<ListInstitutions v-if="addInst === false"/>
<Can I="create" an="Institution">
<AddInstitution v-if="addInst === true" @created="closeModal"/>
</Can>
</div>
</template>
<script>
import AddInstitution from "@/components/institution/AddInstitution";
import ListInstitutions from "@/components/institution/ListInstitutions";
import { Can } from "@casl/vue";
export default {
name: 'InstitutionPage',
components: {AddInstitution, ListInstitutions, Can},
data() {
return {
addInst: false,
action: this.addInst ? 'Institutions' : 'Add Institution'
}
},
methods: {
closeModal() {
this.addInst = false
}
}
}
</script>