首页 文章

从vuex api请求初始化Vue组件中的数据

提问于
浏览
2

从vuex存储中的异步api调用初始化Vue组件中的数据的最简单方法是什么 . 组件在数据可用之前安装 .

考虑:

export default {
data () {
  return {
    loanAmount: 300000,
    thirtyFixedAPR: null,
    fifteenFixedAPR: null,
    fiveArmAPR: null
  }
},
methods: {
  fetchRates () {
    this.thirtyFixedAPR = this.$store.state.rates.thirtyFixed.apr
    this.fifteenFixedAPR = this.$store.state.rates.fifteenFixed.apr
    this.fiveArmAPR = this.$store.state.rates.fiveArm.apr
  }
},
mounted () {
  this.fetchRates()
}}

我希望在vuex存储中的api调用完成后调用fetchRates方法一次 . 我使用计算属性,但我只想初始化数据,而不是观察它 . 我已经尝试了一些使用看起来不太优雅的观察者的解决方法,我觉得有一个更简单的答案 .

谢谢你的帮助 .

1 回答

  • 1

    您需要在Vuex中使用subscribe .

    基本上;

    const myMutationListener = this.$store.subscribe((mutation, state) => {
      if (mutation.type === 'MY_MUTATION_INSIDE_VUEX'){
       this.parameter1 = mutation.payload.parameter1
       this.parameter2 = mutation.payload.parameter2
      }
    })
    

相关问题