【发布时间】:2021-10-19 15:38:41
【问题描述】:
我有Vuejs/Nuxtjs 应用程序,在它被Vuex action 修改后,我需要在其中访问Vuex 存储state。目前,当我尝试运行 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,但都不起作用
任何建议将不胜感激。提前致谢。
【问题讨论】:
-
您的代码不会等待异步操作完成。尝试在计算属性中添加以下
this.formData.returnValue = this.$store.state.modules.DataStore.data。 -
尝试了 Async 和 await 但两者都不起作用 - 你到底尝试了什么?他们应该没有工作,因为他们没有被正确使用。目前你根本没有链接承诺,所以代码显然不会等待它们。
标签: javascript vue.js nuxt.js vuex