Skip to content
This repository has been archived by the owner on Mar 2, 2022. It is now read-only.

Latest commit

 

History

History
 
 

casl-vue

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

CASL Vue @casl/vue NPM version CASL Documentation CASL Join the chat at https://gitter.im/stalniy-casl/casl

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.

Installation

npm install @casl/vue @casl/ability

Getting Started

1. Including plugin

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)

2. Defining Abilities

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.

3. Check permissios in templates

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 help?

Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for contributing

License

MIT License