Directives as functions in Vue 3
mreduar opened this issue · comments
Hi, I am trying to use the directives as functions in Vue 3, but as Vue 3 with Composition API does not have access to this.$gates
then I can't find a way to make it work.
In their documentation there are examples of this, but it doesn't work in vue 3 as usual.
this.$gates.hasRole('admin'); // false
this.$gates.unlessRole('admin'); // true
this.$gates.hasAnyRole('admin|writer'); // true
this.$gates.hasAllRoles('admin|writer'); // false
I have also tried with
import { getCurrentInstance } from "vue";
const app = getCurrentInstance();
app.$gates.hasRole('admin');
But it doesn't work for me.
I am using Laravel Inertia and I implement it as follows
// resources/js/Plugins/Permissions.js
import { usePage } from '@inertiajs/inertia-vue3'
export default {
install: (app) => {
app.mixin({
mounted() {
let user = usePage().props.value.auth.user
if (user) {
let authRoles = user.roleNames;
let authPermissions = user.permissionNames;
this.$gates.setRoles(authRoles);
this.$gates.setPermissions(authPermissions);
}
}
})
}
}
// resources/js/app.js
require('./bootstrap');
import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';
import VueGates from 'vue-gates';
import Permissions from './Plugins/Permissions';
import store from './Plugins/Store';
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => require(`./Pages/${name}.vue`),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.use(VueGates) // Use package here
.use(Permissions) // and here my implementation
.use(store)
.mixin({ methods: { route } })
.mount(el);
},
});
InertiaProgress.init({ color: '#4B5563' });
Everything works fine in the template directives, like v-role
but I would like to be able to use it as functions as well.
Any ideas?
No suggestions?
@mreduar did you found a solution?
Unfortunately I did not find a solution, I am still open to a solution.
For now I have made a reusable function that checks the user roles and I can use it as a function.
const hasRole = (user, role) => {
const roles = user.roleNames;
return roles.some((userRole) => userRole === role);
};
export { hasRole, ... };
import { hasRole } from '@/utils/generalFunctions';
const user = usePage().props.value.auth.user;;
const isAdmin = hasRole(user, 'admin');
If someone finds a solution, do not hesitate to share it.