Blog>
Snippets

Permission-based Disable Directive

Create a custom directive that disables an input or button element based on user permissions provided as a directive's value.
Vue.directive('disable-if-not-allowed', {
  bind: function(el, binding, vnode) {
    // Get the user permissions from the directive's value
    const userPermissions = binding.value;

    // Define the required permission for the element
    const requiredPermission = el.getAttribute('required-permission');

    // Disable the element if the user does not have the required permission
    if (!userPermissions.includes(requiredPermission)) {
      el.disabled = true;
    }
  }
});
This code registers a custom Vue.js directive called 'disable-if-not-allowed'. When bound to an element, it checks if the user has a certain permission. If the user does not have the specified permission, the element is disabled. The directive expects the `required-permission` attribute on the element for comparing against user permissions.
// Usage in HTML
// <button v-disable-if-not-allowed="['read', 'write']" required-permission="edit">Edit</button>

// In this example, the button will be disabled because the user does not have the 'edit' permission.
This piece of code exemplifies how to use the custom 'disable-if-not-allowed' directive in HTML. It is applied to a button element, which would be disabled if the user does not have the 'edit' permission.