cvdv
cvdv

Reputation: 2932

Bind vuex state to this in data()?

I'm upgrading vuex to 2.0 and was wondering if its possible use mapstate/getters before data gets initialized?

In Vuex 1.0, the vuex state would be mapped before data() did so I could just call this and then the state I wanted to access

import { mapGetters } from 'vuex'

export default {
  vuex: {
    getters: {
      userSettings: ({ settings }) => settings.userSettings,
    }
  },
  data: function () {
    return {
      sendEmails: this.userSettings.sendEmails
    }
  }
}

But in Vuex 2.0, I have to do this.$store.state.settings.UserSettings.sendEmails

import { mapGetters, mapState } from 'vuex'

export default {
data: function () {
   return {
    sendEmails: this.$store.state.settings.UserSettings.sendEmails
   }
}
computed: {
  ...mapGetters({
    settings: "settings"
  })
}

Is there a way to have that state initialized before data()? I have multiple components that make use of the state in the data initialization and having to call this.$store.state? I realize I can do some destructuring but I was just wondering if I could avoid that.

Upvotes: 6

Views: 8667

Answers (1)

whoacowboy
whoacowboy

Reputation: 7447

I would set sendEmails in mounted

import { mapGetters, mapState } from 'vuex'

export default {
    data: function () {
       return {
        sendEmails: []
       }
    }

    computed: {
      ...mapGetters({
        settings: "settings"
      })
    },

    mounted: function() {
       if (this.settings.UserSettings){
          this.sendEmails = this.settings.UserSettings.sendEmails
       }
    }
}

Upvotes: 7

Related Questions