What is the correct way to update an object reference using a Vuex mutation?

怎甘沉沦 提交于 2019-12-11 17:24:41

问题


When an object reference is passed to a Vue child component, and I want to update the value of one of the object's properties (using Vuex), the easiest way to do it is by passing the object reference and the new value to the mutation. The mutation then simply updates the property of the passed object.

Is this legitimate? It seems bit too easy, and bordering on redundant (because I could do the reassignment in the component itself), except that the mutation can now be tracked.

The alternative would be to pass an object identifier as part of the payload, and get the mutation to search the store and retrieve it. I don't fancy doing this work if I don't have too though.


回答1:


Well consider it is as a magic or a boon, but that's how vue works (simple, clear and intuitive) Thanks to Evan and team for that.

If you are coming from React or Angular, you might think it's way too easy and may not be convinced with it legitimisation. But believe me that's how much cool is vue.

Let me explain you why you can't directly change the mutation

First you will be greeted with this

Error: [vuex] Do not mutate vuex store state outside mutation handlers. at assert

It's a bad practice to update the state without mutations, because Vuex state is similar to Vue component data in terms of reactivity.

Mutations Follow Vue's Reactivity Rules Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically.

It the whole point of committing the mutation is that it won't let the state change when you are committing it.

Within Store.commit()'s code, it executes the mutation code through a _withCommit() internal function.

All that this _withCommit() does is it sets a flag this._committing to true and then executes the mutation code (and returns _committing to false after the exection).

The Vuex store is then watching the states' variables and if it notices (aka the watcher triggers) that the variable changed while the _committing flag was false it throws the warning.

You can read more about why not change the state directly in this answer

So What's the best way to update an object.

  1. Dispatch action with payload (optional)
  2. Action commits mutation with payload
  3. Mutation updates object with payload.


来源:https://stackoverflow.com/questions/51257306/what-is-the-correct-way-to-update-an-object-reference-using-a-vuex-mutation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!