Implementing reactive Vue 3 v-permission directive
The directive uses a reactive Pinia UserStore to watch the user's role and conditionally removes or reinserts elements in the DOM with comment placeholders. When the WebSocket updates the store’s role, the directive instantly re-evaluates permissions and updates the DOM accordingly, ensuring dynamic role changes reflect immediately.
You can treat it exactly like a v-if: mount the element, replace it with a comment when it’s not allowed, and put it back when it is. The only thing the directive needs to “listen” to is the reactive role in your store – as soon as the store is updated from your WebSocket handler the directive’s watch will fire.
Here’s a complete example using Pinia for the user store.
// stores/user.ts
import {defineStore} from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
role: 'guest' as string,
}),
actions: {
setRole(role: string) {
this.role = role
},
},
})
Wire your WebSocket to the store somewhere in your app bootstrap:
// e.g. in App.vue setup() or a dedicated service
import {useUserStore} from '@/stores/user'
const userStore = useUserStore()
const ws = new WebSocket('wss://example.com/roles')
ws.onmessage = evt => {
const {role} = JSON.parse(evt.data)
userStore.setRole(role) // triggers reactivity
}
Custom directive:
// directives/permission.ts
import {DirectiveBinding, VNode, watch} from 'vue'
import {useUserStore} from '@/stores/user'
type Roles = string | string[]
interface PermEl extends HTMLElement {
__vPerm?: {
stop: () => void
placeholder: Comment
removed: boolean
parent: Node | null
next: ChildNode | null
}
}
export default {
mounted(el: PermEl, binding: DirectiveBinding<Roles>, vnode: VNode) {
const userStore = useUserStore()
const placeholder = document.createComment('v-permission')
const getAllowed = () =>
Array.isArray(binding.value) ? binding.value : [binding.value]
const state = (el.__vPerm = {
stop: () => {},
placeholder,
removed: false,
parent: null,
next: null,
})
const update = () => {
const allowed = getAllowed().includes(userStore.role)
if (!allowed && !state.removed) {
state.parent = el.parentNode
state.next = el.nextSibling
state.parent?.replaceChild(state.placeholder, el)
state.removed = true
} else if (allowed && state.removed) {
const parent = state.parent
if (parent) {
parent.insertBefore(el, state.next)
parent.removeChild(state.placeholder)
state.removed = false
}
}
}
state.stop = watch(
() => userStore.role,
update,
{immediate: true},
)
},
updated(el: PermEl, binding: DirectiveBinding<Roles>) {
// if allowed roles list itself is reactive, trigger update here if needed
},
beforeUnmount(el: PermEl) {
el.__vPerm?.stop()
el.__vPerm = undefined
},
}
Register the directive once on your app:
// main.ts
import {createApp} from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'
import vPermission from './directives/permission'
const app = createApp(App)
app.use(createPinia())
app.directive('permission', vPermission)
app.mount('#app')
And use it in templates:
<!-- Only admins and managers can see this button -->
<button v-permission="['admin','manager']">Delete user</button>
<!-- Only moderators can see this -->
<div v-permission="'moderator'">Moderation tools</div>
When your WebSocket pushes a new role into the store, the watch in the directive fires immediately and swaps the element in or out of the DOM accordingly. No manual event bus is needed because the store is already reactive.