Vuex:直接从组件跳过动作并直接提交突变

JavaScript

Sam神乐

2020-03-15

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

  1. 调度一个action方法,该方法将进一步commit mutation,最终将改变状态。

  2. 第二种方法是mutation直接从组件提交,然后突变方法将更改状态。

当前,我正在使用像这样的第一种方法:

在组件中:

this.$store.dispatch('updateNotice', 'This is some notice')

在行动中:

updateNotice ({state, getters, commit}, payload) { commit('UPDATE_NOTICE', payload) }

在变异中:

UPDATE_NOTICE (state, payload) { state.notice = payload }

您可能已经注意到,我使用该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.

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

第1622篇《Vuex:直接从组件跳过动作并直接提交突变》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
宝儿乐 2020.03.15

在您的情况下,可以使用...mapMutations$store实例直接在组件中提交突变

由于您询问了最佳实践,因此存在动作的主要原因是异步性。突变不能是异步的,而动作可以是异步的,尽管您可以$store.commit直接在Component中调用,这将是一个同步事件,但是dispatch与Mutations不同,当您调用提交时,可以在操作块内异步处理提交。

因此,最佳实践是在必须异步处理状态时使用动作来对状态进行修改,例如,在这种情况下,您需要先进行API调用,然后再提交状态更改,在这种情况下,使用动作是一个好主意。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android