Created
April 7, 2021 09:39
-
-
Save Aslam97/6a27dc397c6a62ab3a6b3e6fa680bb76 to your computer and use it in GitHub Desktop.
Vue Permission Directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Example = { | |
data() { | |
return { | |
users: [ | |
{ | |
id: 1, name: 'Aslam', permissions: ['view'] | |
}, | |
{ | |
id: 2, name: 'Jonwik', permissions: [] | |
} | |
], | |
activeUserId: 2 | |
} | |
}, | |
computed: { | |
currentUser() { | |
return this.users.find(user => user.id === this.activeUserId) | |
} | |
}, | |
methods: { | |
setActiveUser(id) { | |
this.activeUserId = id | |
} | |
} | |
} | |
const app = Vue.createApp(Example); | |
app.directive('can', { | |
mounted(el, binding, vnode) { | |
const vm = binding.instance | |
const { value } = binding | |
let { permissions } = vm.currentUser; | |
if (value && value instanceof Array && value.length > 0) { | |
const requiredPermissions = value | |
const hasPermission = permissions.some( | |
(permission) => requiredPermissions.includes(permission) | |
) | |
if (!hasPermission) { | |
el.parentNode && el.parentNode.removeChild(el) | |
} | |
} | |
}, | |
}) | |
app.mount('#app') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment