从 Vuex 操作返回 Promise [英] Returning Promises from Vuex actions

查看:179
本文介绍了从 Vuex 操作返回 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I recently started migrating things from jQ to a more structured framework being VueJS, and I love it!

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

Conceptually, Vuex has been a bit of a paradigm shift for me, but I'm confident I know what its all about now, and totally get it! But there exist a few little grey areas, mostly from an implementation standpoint.

我觉得这个设计不错,但不知道是否与Vuex相矛盾循环单向数据流.

This one I feel is good by design, but don't know if it contradicts the Vuex cycle of uni-directional data flow.

基本上,从动作返回一个承诺(类似)对象是否被认为是一种好习惯?我将这些视为异步包装器,具有失败状态等,因此似乎很适合返回承诺.相反,mutators 只是改变事物,并且是存储/模块中的纯结构.

Basically, is it considered good practice to return a promise(-like) object from an action? I treat these as async wrappers, with states of failure and the like, so seems like a good fit to return a promise. Contrarily mutators just change things, and are the pure structures within a store/module.

推荐答案

Vuex 中的

actions 是异步的.让调用函数(动作的发起者)知道动作完成的唯一方法是返回一个 Promise 并稍后解析它.

actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.

这是一个例子:myAction 返回一个 Promise,进行一个 http 调用,然后解析或拒绝 Promise - 全部异步>

Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later - all asynchronously

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 组件的一些示例代码:

Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:

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 是非常有益的.否则,操作发起者将无法知道正在发生的事情以及事情何时稳定到足以在用户界面上显示某些内容.

As you can see above, it is highly beneficial for actions to return a Promise. Otherwise there is no way for the action initiator to know what is happening and when things are stable enough to show something on the user interface.

关于 mutators 的最后一点 - 正如您正确指出的,它们是同步的.它们更改 state 中的内容,通常从 actions 调用.没有必要将 Promisesmutators 混合在一起,因为 actions 会处理那部分.

And a last note regarding mutators - as you rightly pointed out, they are synchronous. They change stuff in the state, and are usually called from actions. There is no need to mix Promises with mutators, as the actions handle that part.

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

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

If you access data like this.$store.state["your data key"] in your components, then the data flow is uni-directional.

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

The promise from action is only to let the component know that action is complete.

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

The component may either take data from promise resolve function in the above example (not uni-directional, therefore not recommended), or directly from $store.state["your data key"] which is unidirectional and follows the vuex data lifecycle.

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

The above paragraph assumes your mutator uses Vue.set(state, "your data key", http_data), once the http call is completed in your action.

这篇关于从 Vuex 操作返回 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆