[Vue] Brief summary of the underlying principles of MVVM and two-way binding

First, we must first understand a concept, what is MVVM?

MVVM:
M: Data model layer, responsible for data processing.
V: view layer, display view.
VM: The view model layer, involving two-way binding.
The input box changes -data changes. view=>data
data change-node change. data=>view

2. Summary of the underlying principle of two-way binding:

method : through data hijacking Object.defineProperty and publish-subscribe mode.
There is a noun involved here, what is data hijacking? In a word: add monitoring to the data, and once it changes, perform the process of modifying the view operation.

Summary of the concise version ① : Monitor data changes through Object.defineProperty, and then notify the subscriber (watcher), and the subscriber triggers a response callback.

Summary of Supplemental Concise Version ② : Monitor property changes through the listener Observer-Use Object.defineProperty(), and notify the subscribers through the subscriber Dep. The subscriber Dep is to subscribe to the change of the listener. When the change triggers the update in the parser compile function.

Supplementary version summary ③: There is a core method in the vue source code called defineReactive(), which converts non-detection to detection. Specific logic: through the listener Observer-using Object.defineProperty() data hijacking, each state data will be hijacked, the object will be traversed, and setters and getters will be added to each property. So if we assign a value, the setter will listen. At the same time, create a subscriber Dep, and add a subscriber watcher to each dependent. In this way, when the data changes, the corresponding setter will be triggered, so that Dep will issue a notification to notify each subscriber watcher, and then the watcher will update the corresponding data. That is to trigger the update function in the parser compile.

Specific steps:
1. Implement a listener Observer - Use Object.defineProperty() to monitor property changes. (Use Object.defineProperty() to add setters and getters to properties. In this way, if our assignment changes, the setter will be triggered and we will listen to it)
2. Implement a parser Compile - parse Vue template instructions and bind updates Function, add subscribers to monitor data, once the data changes, call the update function to update the data.
3. Implement Subscriber Watcher - Subscribe to the property change of Observer, when the change occurs, trigger the corresponding update function in the parser Compile.
4. Implement the subscriber Dep - notify the subscriber when there is a change - used to collect subscribers and manage listeners and subscribers in a unified manner.

Attached is a picture I found on the Internet, which feels very clear, for your reference:

Guess you like

Origin blog.csdn.net/m0_71981318/article/details/125403283