Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 588
cvdv Avatar asked Apr 12 '17 16:04

cvdv


1 Answers

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
       }
    }
}
like image 143
whoacowboy Avatar answered Sep 18 '22 18:09

whoacowboy