vuex unidirectional data flow, the recommended commit to change state data is very cumbersome to write, because changing data may require a lot of commit functions.
According to my understanding, one-way data flow is mainly to avoid data confusion and facilitate debugging. To put it bluntly, it is a data that has changed, what prompted him to change.
Data flow is always the same direction, and the downstream has no right to change the data, so the same method as the data distribution center needs to change the data.
Single-item data flow is indeed necessary for react, but is it so necessary for vue?
vue uses data dependency updates, and all necessary data are processed. When assigning values to the data, all doms that use this data will be notified to update, regardless of whether it is a dom formed by the parent or child.
When using vuex, it is recommended to use commit to modify the state data.
advantage
- It is easy to debug. When the data changes, you can see in the vuetools tool which function modified the state value.
shortcoming
- Using commit to modify data may cause many mutation functions to be written.
- Some performance will be lost. Because the new data requires reconfiguration of watcher.
optimization
For those who use commit to save state data, the following method can be used:
Pass the path of a string and the value that needs to be modified. If path='' is converted to = 'needsave', this achieves a commit to solve all saved problems.
// Functions in mutationssave(state, { path, data }) { if (!path ) { throw new Error('need path') } const keyPath = ('.') let needSave = state for (let i = 0; i < - 1; i++) { needSave = needSave[keyPath[i]] if(!needSave) { throw new Error(`error path: ${keyPath[i]}`) } } needSave[keyPath[ - 1]] = data }, // use('save', {path:'', data:val}) // result = 'I need to save data'
In the component
//If you want to bind the value in a vuex bidirectionally.<input v-model="c"> //script computed: { c: { get(){ return }, set(val) { ('save', {path:'', data:val}) } } } // This enables two-way binding in the component,And usecommitChangestateValues in,vuexThere will be no errors when using strict mode。
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.