Vue one-way data flow

1. One-way data flow

 Data is generally transmitted from the parent component to the child component, and the child component has no right to directly modify the data transmitted from the parent component, that is, the data directly obtained by the child component from props can only use $emit to send an event, requesting the parent component to modify the data and then transmit it to subcomponents. Updates to parent property values ​​flow down to child components. Every time the parent component is updated, all props in the child component will be refreshed with the latest values. This is unidirectional data flow  (data flow refers to the flow of data between components).

Although vue has a two-way binding v-model, the data transfer between vue and react parent-child components still follows a one-way data flow. The parent component can pass props to the child component, but the child component cannot modify the props passed by the parent component. , the child component can only notify the parent component to make data changes through events, as shown in the figure:

Subcomponents can only send events through $meit to notify the parent component to modify data

Advantages: All state changes can be recorded and tracked, and the source is easy to trace; there is only one copy of all data, and only one entry and exit for component data, making the program more intuitive and easier to understand, and conducive to application maintainability.

Second, the difference between one-way data flow and two-way data binding

The actual performance of one-way data flow in Vue is: when the data in the Model changes, the value in the View will be modified one-way, and when the value in the View changes, the Model will not perceive it. The practical application is v-bind one-way data.

Two-way data binding is more View changes will be notified to the Model layer. That is, the concrete implementation of MVVM. No matter the value in Model or View changes, it will be notified to the other party through ViewModel to achieve synchronization. The practical application is v-model two-way data binding. 


3. Summary

One-way data flow is to notify the View layer of changes in the Model layer through props for modification.
Two-way data binding is implemented through the set() and get() methods of Object.defineProperty(). When one party changes, the other party will receive a reminder of the updated value, thereby realizing synchronous data changes.

Guess you like

Origin blog.csdn.net/qq_34402069/article/details/128980547