This package allows to integrate @casl/ability into Vue application. So, you can show or hide UI elements based on user ability to see them.
npm install @casl/vue @casl/ability
This package provides Vue plugin which defines $ability
object and $can
method for all components
import { abilitiesPlugin } from '@casl/vue'
import Vue from 'vue'
Vue.use(abilitiesPlugin)
By default, $ability
object is an empty Ability
instance. So, you either need to update it or provide your own.
In case if you want to provide your own, just define it using AbilityBuilder
or whatever way you prefer:
// ability.js
import { AbilityBuilder } from '@casl/ability'
export default AbilityBuilder.define(can => {
can('read', 'all')
})
And just pass it as an argument to abilitiesPlugin
:
import { abilitiesPlugin } from '@casl/vue'
import Vue from 'vue'
import ability from './ability'
Vue.use(abilitiesPlugin, ability)
Alternatively, you can just update existing instance, for example, in SignIn.vue
component when receive rules list from server API (or other sources).
<template>
<form @submit.prevent="login">
<input type="email" v-model="email" />
<input type="password" v-model="password" />
<button type="submit">Login</button>
</form>
</template>
<script>
export default {
name: 'SignIn',
data: () => ({
email: '',
password: ''
}),
methods: {
login() {
const { email, password } = this
return fetch('path/to/api/login', { method: 'POST', body: JSON.stringify({ email, password }) })
.then(response => response.json())
.then(session => this.$ability.update(session.rules))
}
}
}
</script>
Obviously, in this case your server API should provide the list of user abilities in rules
field of the response.
See @casl/ability package for more information on how to define abilities.
To check permissions in any component you can use $can
method:
<template>
<div v-if="$can('create', 'Post')">
<a @click="createPost">Add Post</a>
</div>
</template>
See casl-vue-example for more examples.
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for contributing