Search code examples
nuxt.jsvuex

Access vuex store getter in nuxt data


I need to set up some data in one of my pages in a Nuxt app but that data depends on the value of a variable that I am getting via a getter from my vuex store. Why can't I do it like this?

export default {
  data() {
    return {
      logo: this.currentPlayer.logo,
    }
  },
  computed: {
    ...mapGetters({
      currentPlayer: 'players/current',
    }),
  },
}

If I try and use this, I get

Property or method "logo" is not defined on the instance but referenced during render

Solution

  • If you don't need to assign a new value to logo at anytime in your logic, you can just make it a computed property and it should work fine:

    computed: {
       ...mapGetters({
           currentPlayer: 'players/current',
       }),
        
       logo() {
           return this.currentPlayer?.logo;
       },
    },
    

    However, if you need to keep it inside data to be able to re-assign it later, you can work around it by initializing logo at the mounted() hook:

    mounted() {
        this.logo = this.currentPlayer?.logo;
    }