1๐
โ
You already have a user store that can be injected into any component.
I suggest computing often-used keys like isAdmin
, isSuperAdmin
in the store:
const isAdmin computed(() => hasRole('admin'))
In your components, you can use the following pattern to conditionally render items:
<template>
<div v-if="isAdmin">
<h1>Super Secret Stuff</h1>
</div>
</template>
<script setup>
const { isAdmin } = useUserStore()
</script>
This circumvents direct DOM manipulation, which is always a pain and often a bad practice.
๐คBarthy
1๐
I think that using directives for this purpose, is not the right way, in order to avoid component rendering.
To avoid a component to be rendered you should, insted, use the v-if
condition.
To share the logic of hasRole
between your component, you can use mixins, or just write a small plugin you can add to Vue app.
๐คMario Santini
0๐
Here is the corrected code I have.
import {useUserStore} from "@/stores/UserStore.js";
export default {
inserted(el, binding, vnode) {
const { value } = binding
const super_admin = "admin";
const userStore = useUserStore()
await userStore.fill()
const roles = userStore.getUser.roles
if (value && value instanceof Array && value.length > 0) {
const roleFlag = value
const hasRole = roles.some(role => {
return super_admin === role || roleFlag.includes(role)
})
if (!hasRole) {
el.parentNode && el.parentNode.removeChild(el)
}
} else {
throw new Error(`Missing role value"`)
}
}
}
Source:stackexchange.com