Search code examples
vue.jsvuex

Vuex Return boolean?


I'm trying to make a function that I can call in my templates called hasPermission with a string. However when I call it, vuex returns a promise object. Is there anyway I can make it return a boolean?

hasPermission({ state }, permission) {
  for (var i = 0; i < state.user.permissions.length; i++) {
    var perm = state.user.permissions[i];
    if (perm.name == permission) {
      return true;
    }
  }
  return false;
}

I want to simply be able to call it like v-if="hasPermission("test") and then show based off of the response. However I'm having a bit of a hard time doing this. Would love any advice you can give :)


Solution

  • You can make hasPermission a method-style getter:

    getters: {
      hasPermission: (state) => (permission) => {
        for (var i = 0; i < state.user.permissions.length; i++) {
          var perm = state.user.permissions[i];
          if (perm.name == permission) {
            return true;
          }
        }
        return false;
      }
    }
    

    Use mapGetters to include it in the component:

    import { mapGetters } from 'vuex';
    
    computed: {
      ...mapGetters(['hasPermission'])
    }
    

    Use it in the template like:

    v-if="hasPermission('test')"
    

    Just keep in mind these getters aren't cached like normal getters, but then neither are actions.

    Here is a demo