gpt4 book ai didi

promise - 从 Vuex 操作返回 Promise

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:16 24 4
gpt4 key购买 nike

我最近开始将一些东西从 jQ 迁移到一个更结构化的框架 VueJS,我喜欢它!

从概念上讲,Vuex 对我来说有点范式转变,但我相信我现在知道它的全部内容,并且完全理解它!但是存在一些小的灰色区域,主要是从实现的角度来看。

这个我感觉设计的不错,不知道和Vuex有没有矛盾cycle单向数据流。

基本上,从操作中返回一个 promise(类似)对象被认为是好的做法吗?我将它们视为异步包装器,具有失败状态等,因此看起来很适合返回 promise 。相反,修改器只是改变事物,并且是存储/模块中的纯结构。

最佳答案

actions 在 Vuex 中是异步的。让调用函数( Action 的发起者)知道 Action 已完成的唯一方法是返回一个 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 中调用。无需将 Promisesmutators 混合,因为 actions 会处理该部分。

编辑:我对单向数据流的Vuex循环的看法:

如果您在组件中访问像 this.$store.state["your data key"] 这样的数据,那么数据流是单向的。

action 的 promise 只是让组件知道 action 已经完成。

组件可以从上面例子中的 promise resolve 函数中获取数据(不是单向的,因此不推荐),或者直接从 $store.state["your data key"] 中获取数据是单向的,遵循 vuex 数据生命周期。

上面的段落假设你的 mutator 使用 Vue.set(state, "your data key", http_data),一旦 http 调用在你的操作中完成。

关于promise - 从 Vuex 操作返回 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com