usePermissions
Asking what the current user may do. Two functions over CASL, in the same action, subject grammar as the rules.
Import
ts
import { usePermissions } from '@shared/composables/usePermissions'Signature
ts
function usePermissions(): {
can: (action: string, subject: string) => boolean
cannot: (action: string, subject: string) => boolean
}Returns
| Member | Type | Description |
|---|---|---|
can | (action, subject) => boolean | Whether the ability allows it. |
cannot | (action, subject) => boolean | The negation, for readable templates. |
Example
vue
<script setup lang="ts">
import { usePermissions } from '@shared/composables/usePermissions'
import { computed } from 'vue'
const { can, cannot } = usePermissions()
const mayPublish = computed(() => can('publish', 'Article'))
function publish() {}
</script>
<template>
<div class="space-y-2">
<button type="button" :disabled="!mayPublish" @click="publish()">
Publish
</button>
<p v-if="cannot('publish', 'Article')">
Only an editor can publish.
</p>
</div>
</template>Notes
- They are plain functions, not computeds.
@casl/vuealready makes a template re-render when the rules update, so wrapping each call in acomputedwould add a layer for nothing. In script, where you want a derived ref, wrap it yourself — asmayPublishdoes above. - The rules come from the session.
useAuthcallsupdateAbilityon login, refresh and bootstrap, and clears them on logout. - The subject is the string your rules use, conventionally the model name in Pascal case.
- Like every client-side check, this is for the interface. The backend decides.
Related
v-permission— the same check as a directive.useNavPermission— the menu's gate, which lets guests see everything.- Auth and permissions — where the rules come from.
- Permissions — the guide.