在data()中将vuex状态绑定到此状态?

时间:2017-04-12 16:55:02

标签: javascript vue.js vuejs2 vuex

我将vuex升级到2.0,并想知道在数据初始化之前它是否可能使用mapstate / getter?

在Vuex 1.0中,vuex状态将在data()之前映射,因此我可以调用this然后调用我想要访问的状态

import { mapGetters } from 'vuex'

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

但是在Vuex 2.0中,我必须做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"
  })
}

有没有办法在data()之前初始化该状态?我有多个组件在数据初始化中使用状态并且必须调用this.$store.state?我意识到我可以做一些解构,但我只是想知道我是否可以避免这种情况。

1 个答案:

答案 0 :(得分:2)

我会在sendEmails

中设置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
       }
    }
}