actions
在 Vuex 中是异步的。让调用函数(动作的发起者)知道动作已完成的唯一方法是返回一个 Promise 并稍后解决它。
这是一个示例:myAction
返回 a 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
返回 a是非常有益的Promise
。否则,动作发起者无法知道正在发生的事情以及事情何时足够稳定以在用户界面上显示某些内容。
最后一点关于mutators
- 正如你正确指出的那样,它们是同步的。它们在 中更改内容state
,并且通常从 中调用actions
。没有必要Promises
与mutators
, 作为actions
手柄那部分混合。
编辑:我对单向数据流的 Vuex 循环的看法:
如果您访问this.$store.state["your data key"]
组件中的数据,那么数据流是单向的。
行动的承诺只是让组件知道行动已经完成。
组件可以从上面示例中的 promise resolve 函数中获取数据(不是单向的,因此不推荐),或者直接从$store.state["your data key"]
它是单向的并且遵循 vuex 数据生命周期。
上述段落假设您的 mutator 使用Vue.set(state, "your data key", http_data)
,一旦在您的操作中完成了 http 调用。