首页 > 解决方案 > 如何在访问 Vue Store 状态之前等待操作完成?

问题描述

我有一个应用程序,在它被修改后Vuejs/Nuxtjs我需要在其中访问一个Vuex商店。目前,当我尝试运行然后我得到旧状态而不是之后更新的状态。stateVuex actionactionassignmentaction

如何让代码等待action完成然后运行下一条语句?以下是我目前拥有的代码:Vuejs 组件:

<template>
  <div>
    <input v-model="formData.value" type="text">
    <button @click="performAction">
      Click Me
    </button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      formData: {
        value: '',
        returnValue: ''
      }
    }
  },
  methods: {
    performAction () {
      // Set the value within the Vuex Store
      this.$store.commit('modules/DataStore/populateData', this.formData.value)

      // Perform the Action
      this.$store.dispatch('modules/DataStore/getData').then(() => {
        console.log("AFTER COMPLETE ACTION")
      })

      // Assign the update value to the variable
      this.formData.returnValue = this.$store.state.modules.DataStore.data
    }
  }
}
</script>

<style>
</style>

Vuex商店:

export const state = () => ({
  data:''
})

export const mutations = {
  populateData (state, data) {
    state.data = data
  }
}

export const actions = {
    getData ({ commit, state, dispatch }) {
        const headers = { 'Content-Type': 'application/json' }
        this.$axios
            .post('/getUrlData', state.data, { headers })
            .then((response) => {
                console.log("WITHIN RESPONSE")
                commit('populateData',response.data)
            })
            .catch((error) => {
                commit('populateData', 'Unable to obtain data, Error : ' + error)
            })
    }
}

以下是我尝试过的东西,目前没有任何效果:

  1. 我试过这个.then()功能。
  2. 我试过了Asyncawait但两者都不起作用

任何建议将不胜感激。提前致谢。

标签: javascriptvue.jsnuxt.jsvuex

解决方案


您可以在 vuex 中创建 getter:

export const getters = {
  getData: (state) => state.data,
};
export const actions = {
  async setData ({ commit }, data) {
    const headers = { 'Content-Type': 'application/json' }
    await this.$axios
      .post('/getUrlData', data, { headers })
      .then((response) => {
        console.log("WITHIN RESPONSE")
        commit('populateData',response.data)
      })
      .catch((error) => {
        commit('populateData', 'Unable to obtain data, Error : ' + error)
      })
  }
}

然后在组件中,您可以映射 getter 和操作,并调用它们:

import { mapGetters, mapActions } from 'vuex'

computed: {
...mapGetters(['getData']),
},
methods: {
  ...mapActions(['performAction']),
 
  async performAction() {
    await this.setData(this.formData.value)
    this.formData.returnValue = this.getData
  }
}

推荐阅读