Skip to content

Instantly share code, notes, and snippets.

@Aslam97
Created April 7, 2021 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aslam97/6a27dc397c6a62ab3a6b3e6fa680bb76 to your computer and use it in GitHub Desktop.
Save Aslam97/6a27dc397c6a62ab3a6b3e6fa680bb76 to your computer and use it in GitHub Desktop.
Vue Permission Directive
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