Vuex中的actions
是异步的.让调用函数(操作的发起方)知道操作已完成的唯一方法是返回一个promise ,然后解决它.
下面是一个例子:myAction
返回Promise
,进行http调用,然后解析或拒绝Promise
,所有这些都是异步的
actions: {
myAction(context, data) {
return new Promise((resolve, reject) => {
// Do something here... lets say, a http call using vue-resource
this.$http("/api/something").then(response => {
// http success, call the mutator and change something in state
resolve(response); // Let the calling function know that http is done. You may send some data back
}, error => {
// http failed, let the calling function know that action did not work out
reject(error);
})
})
}
}
现在,当Vue组件启动myAction
时,它将获得这个Promise对象,并且可以知道它是否成功.以下是Vue组件的一些示例代码:
export default {
mounted: function() {
// This component just got created. Lets fetch some data here using an action
this.$store.dispatch("myAction").then(response => {
console.log("Got some data, now lets show something in this component")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
})
}
}
正如你在上面看到的,actions
返回Promise
是非常有益的.否则,动作发起人就无法知道发生了什么,以及什么时候事情足够稳定,可以在用户界面上显示一些东西.
最后一点是关于mutators
的——正如你正确指出的,它们是同步的.它们在state
中改变内容,通常从actions
开始调用.无需将Promises
与mutators
混合,因为actions
处理该部分.
Edit: My views on the Vuex cycle of uni-directional data flow:
如果访问组件中的数据(如this.$store.state["your data key"]
),则数据流是单向的.
行动的promise 只是让组件知道行动已经完成.
组件可以从上述示例中的promise resolve函数中获取数据(不是单向的,因此不推荐),也可以直接从$store.state["your data key"]
中获取数据,$store.state["your data key"]
是单向的,遵循vuex数据生命周期.
以上段落假设,一旦http调用在您的操作中完成,mutator使用Vue.set(state, "your data key", http_data)
.