I am exploring how to create a custom Vue conditional directive. While I could simply use a global method and call it within a v-if, I prefer the idea of having a dedicated directive for clarity in my code.
My objective is to apply this directive to an element and provide a Guid to it (for managing conditional rendering based on user permissions):
v-permission="'4ECE1FD4-4019-4CA2-AB9E-0A555CCBDB5B'"
Currently, I am using the directive's bind
method to add display: none
to the element, which successfully hides the content. However, for better performance, I would like to avoid rendering the element altogether.
Does anyone have any suggestions on how I can accomplish this?
Here is the snippet of the current directive code:
import Vue from 'vue'
Vue.directive('permission', {
bind: function (el, binding, vnode) {
if (binding.value) {
let hasPermission =
vnode.context.$store.getters.hasApiPermission(binding.value)
if (!hasPermission) {
el.style.display = 'none'
}
} else {
console.error('You must specify a permission ID')
}
}
})