StefR
StefR

Reputation: 111

access a getter from within a vue directive

I'm writing a simple vue directive that returns true if a permission is matched with user permissions that are in the Vuex store. But I'm not able to access the state properly.

I'm able to access the getter store.state.user.user.permissions and also a getter store.getters.currentUserPermissions without any problem from within Vue components.

import store from './store/index';

Vue.directive('can',{
    inserted(el,binding){
        let permissions = store.getters.currentUserPermissions;

        console.log(permissions);
        if(!permissions.includes(binding.value)){
            el.style.display = 'none';
        }
    }
});

the console returns undefined

But when I log store.getters in the console, I get:

{}
currentUserPermissions: (...)
> get currentUserPermissions: f ()
> __proto__: Object

How can I access currentUserPermissions?

Upvotes: 2

Views: 2199

Answers (1)

Vítor Antero
Vítor Antero

Reputation: 116

I went through the same trouble and managed to find a solution. I'll leave it here to help others who may come looking for it.

The third argument of the directive argument, vnode, has access to the store through its $context property. So the code would look like this:

Vue.directive('can',{
  inserted(el,binding,vnode){
    const store = vnode.context.$store;
    let permissions = store.getters.currentUserPermissions;

    console.log(permissions);
    if(!permissions.includes(binding.value)){
      el.style.display = 'none';
    }
  }
});

Please notice that if the desired getter is inside a module, you would have to access it in a different way:

store.getters['<module>/<getter>']

Upvotes: 3

Related Questions