首页 > 解决方案 > vuex 状态预取不起作用

问题描述

我面临一个关于 vuex 的问题,在我的 vue 组件中,我发送了一个存储请求,然后在计算的钩子中我映射了存储状态,并且第一次返回 null 时,我认为它在存储状态之前开始映射。

这是代码index.vue文件代码,

export default {
  name: 'tab_3',
  data () {
    return {
      tableData: []
    }
  },
  beforeCreate () {
    this.$store.dispatch('registerWeb3')
    this.$store.dispatch('getContractInstance')
  },
  computed: mapState({
    coinbase: state => state.web3.coinbase,
    balance: state => state.web3.balance
  }),
  methods: {
    Func: function () {
      console.log(this.coinbase)
      console.log(this.balance)
    }
  },
  beforeMounte () {
    this.Func()
  },
  updated () {
  }
}

这是store.js文件代码:

Vue.use(Vuex)
export const store = new Vuex.Store({
  strict: true,
  state,
  mutations: {
    registerWeb3Instance (state, payload) {
      let result = payload
      let web3Copy = state.web3
      web3Copy.coinbase = result.coinbase
      web3Copy.balance = parseInt(result.balance, 10)
    },
    registerContractInstance (state, payload) {
      state.MyContract = () => payload[0]
      state.TokenContract = () => payload[1]
    }
  },
  actions: {
    registerWeb3 ({commit}) {
      getWeb3.then(result => {
        commit('registerWeb3Instance', result)
      }).catch(e => {
        console.log('error in action registerWeb3', e)
      })
    },
    getContractInstance ({commit}) {
      getContract.then(result => {
        commit('registerContractInstance', result)
      }).catch(e => console.log(e))
    }
  }
})

标签: vue.jsvuejs2vuex

解决方案


推荐阅读