Search code examples
javascriptvue.jsvuejs2vue-componentvuex

Vue - Is it possible to use Vuex getters in the computed property of a component?


In my vuex-store has different variables, for example loggedIn. Now I need to use this variable from the computed section of my component, because I want to filter the array based on the variable value.

Here you can see how I want to use it in my code

<td v-for="(item, index) in navLinks" :item="navLink" :key="index">
  <router-link :to="{ name: item.name }" class="router-links" exact>{{ item.text }}</router-link>
</td>

And this is the relevant part of my script section:

computed: {
  ...mapGetters(['user', 'loggedIn']),
  navLinks: [
    {
      vif: !this.loggedIn,
      name: 'Register',
      text: 'Registrieren',
    },
    {
      vif: this.loggedIn,
      name: 'Logout',
      text: 'Logout',
    },
  ],
},

I always get the error

Uncaught TypeError: Cannot read property 'loggedIn' of undefined

So I think that I can't use Vuex getters before a component mounts because this is not defined..?

If I used navLinks in the data with v-if-directives, I'd get an error because v-if bindings are not allowed with v-for bindings.

So how can I fix my problem?


Solution

  • navLinks should be a function that returns an array :

    computed: {
      ...mapGetters(['user', 'loggedIn']),
      navLinks(){
      return [
        {
          vif: !this.loggedIn,
          name: 'Register',
          text: 'Registrieren',
        },
        {
          vif: this.loggedIn,
          name: 'Logout',
          text: 'Logout',
        },
      ];
     ),
    },