【问题标题】:Initialize data in Vue Component from vuex api request从 vuex api 请求初始化 Vue 组件中的数据
【发布时间】:2023-03-11 22:54:01
【问题描述】:

从 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 store 中的 api 调用完成后调用一次 fetchRates 方法。我会使用计算属性,但我只想初始化数据,而不是观察它。我已经尝试了一些使用看起来不太优雅的观察者的解决方法,我觉得有一个更简单的答案。

感谢您的帮助。

【问题讨论】:

  • 你试过用“created”方法代替mount()吗?
  • 是的。生活方式挂钩的组合似乎不起作用。
  • 如果你延迟了会怎样,所以在mounted()里面让组件等待几秒钟再调用vuex获取数据?
  • 这可能是我尽量避免延误的最简单的解决方案。
  • 是的,我同意。让所有这些属性由 1 个函数返回,并且该函数返回一个承诺,然后你给承诺一个回调并在网络调用完成时提取你的数据。

标签: vue.js vuex


【解决方案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
  }
})

【讨论】:

    猜你喜欢
    • 2020-11-20
    • 2018-06-30
    • 2019-12-21
    • 2020-06-02
    • 2010-09-14
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 2021-06-24
    相关资源
    最近更新 更多