javascript - 如何在访问 Vue Store 状态之前等待操作完成?
问题描述
我有一个应用程序,在它被修改后Vuejs/Nuxtjs
我需要在其中访问一个Vuex
商店。目前,当我尝试运行然后我得到旧状态而不是之后更新的状态。state
Vuex action
action
assignment
action
如何让代码等待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)
})
}
}
以下是我尝试过的东西,目前没有任何效果:
- 我试过这个
.then()
功能。 - 我试过了
Async
,await
但两者都不起作用
任何建议将不胜感激。提前致谢。
解决方案
您可以在 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
}
}
推荐阅读
- c# - 运行时启用的菜单条项目
- zabbix - Zabbix:要更新的项目队列不会减少(在管理选项卡中)
- corda - 无法反序列化 RPC 回复,请求的接口必须仅包含以 'get' 开头的方法,[corda] errorCode 15rlwi0
- r - R中ECDF的显示
- ios - 如何对字典类型中的特定值求和
- html - Bootstrap - 在 safari 中不支持 col-sm-6
- python - 来自网络摄像机的 opencv 流
- bash - 带有 bash 脚本的 Git 镜像卡在 3 for 循环中
- java - AppEngine 上的 HikariCP
- vue.js - 使用 vue + firestore 进行全文搜索的最佳方法