Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex Return boolean?

Tags:

vue.js

vuex

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 :)

like image 570
Kyle B Avatar asked Sep 19 '26 14:09

Kyle B


1 Answers

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

like image 140
Dan Avatar answered Sep 22 '26 16:09

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!