Vuex:跳过操作并直接从组件提交 Mutation [英] Vuex: Skipping Action and committing Mutation directly from Component

查看:29
本文介绍了Vuex:跳过操作并直接从组件提交 Mutation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 vue.js 应用程序中,使用 vuex 作为状态管理存储,我需要简单地更改 vuex 中的属性值.为此,我可以采用两种方法:

In vue.js app, using vuex as state management store, I need to simply change the value of a property in vuex. For this I can follow two methods:

  1. 调度一个action方法,它将进一步提交mutation,最终会改变状态.

  1. Dispatch an action method, which will further commit mutation, which eventually will change the state.

第二种方法是直接从组件提交mutation,然后mutation方法会改变状态.

The second method is to commit the mutation directly from the component and the mutation method will then change the state.

目前,我正在使用第一种方法:

Currently, I'm using first method like this:

在组件中:

this.$store.dispatch('updateNotice', '这是一些通知')

在行动:

updateNotice ({state, getters, commit}, payload) {提交('UPDATE_NOTICE',有效载荷)}

在突变中:

UPDATE_NOTICE(状态,有效载荷){state.notice = 有效载荷}

您可能已经注意到,我使用 action 方法只是为了提交一个单个突变,没有任何其他逻辑或异步功能.

As you might have noticed, I'm using the action method simply to commit a single mutation, without any other logic or async functionality.

我的问题是,在这种情况下,我不应该直接从组件本身提交突变吗?最佳做法是什么?因为在这个简单的例子中使用 action 方法似乎很冗长,没有特定的目的.

My question is, in this case, should I not directly commit the mutation from the component itself? What is the best practice? Since using action method in this simple case seems verbose and serve no specific purpose.

是否有任何理由让我总是commit 来自组件的操作?毕竟,在 vuex 中 ...mapMutations() 有一定存在的理由.

Is there any reason that I should always commit actions from a component? Afterall, in vuex the ...mapMutations() have some reason to exist.

推荐答案

在您的情况下,使用 ...mapMutations$store 直接在组件中提交更改应该没问题 实例.

In your case it should be fine to commit the mutations directly in your components using ...mapMutations or $store instance.

既然您询问了最佳实践,那么 Actions 存在的主要原因是异步性.Mutations 不能是异步的,而 Actions 可以是异步的,虽然你可以直接在组件中调用 $store.commit 这将是一个同步事件,但是当你调用 dispatch 时,提交可以与 Mutations 不同,在操作块内异步处理.

Since you asked the best practice, The primary reason for the existence of Actions is Asynchronicity. Mutations cannot be asynchronous whereas Actions can be, while you can call $store.commit directly in a Component this will be a synchronous event, but when you call dispatch the commit can be handled asynchronously within the action block unlike Mutations.

因此,最佳实践是在必须异步处理状态时使用 Actions 提交对状态的修改,例如在这种情况下,您需要在提交状态更改之前执行 API 调用,使用 Actions 是个好主意.

So the best practice is to use Actions to commit modifications to your state when it has to be handled asynchronously say you need to do an API call before committing the state change in such cases it would be a good idea to use Actions.

这篇关于Vuex:跳过操作并直接从组件提交 Mutation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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