Detailed explanation of MVVM architectural pattern

What is MVVM?

        MVVM is a front-end architectural pattern, and VUE.JS is a set of frameworks based on this pattern.

         (Also based on MVVM architecture: WeChat applet, AngularJS, ReactJs)

What does MVVM consist of?

        MVVM consists of three parts, namely Model, View, ViewModel

        Model: Simply put, it is the variable data in JS

        View: Simply put, it is the HTML element on the page

        ViewModel: It is the core of Vue.js. It is a Vue instance . It has two tools. The function is simply to make  the Model and the View come into contact, and to keep the DOM and data in sync . They are:

                DOM Listeners: After the data on the listening page is changed, it will be updated to the Model synchronously

                Data Bindings: When the data in the Model changes, the corresponding DOM on the page will be re-rendered

Summary of the role of MVVM?

        The architectural pattern of MVVM makes the framework data-driven.

MVVM principle?

Using data hijacking combined with publisher-subscriber pattern

During Vue instantiation

On the one hand: through the Object.defineProperty() method provided by SE5, convert all data in the object into corresponding setter and getter methods.

On the one hand: Initialize the view and subscribe to Watcher to update the view. At this time, Wather will add itself to the message subscriber (Dep), and the initialization is complete.

What happens when the data changes?

When the data changes (triggering the setter), the setter method in the Observer is triggered, and the setter will call Dep.notify() immediately, and Dep starts to traverse all subscribers, and calls the update method of the subscriber. After the subscriber receives the notification Update the view accordingly.

The idea of ​​MVVM?

The status update of DOM allows the MVVM architectural pattern to be completed automatically to reduce developers' operations on DOM.

Observer: A data listener that can monitor all properties of a data object. If there is a change, it can get the latest value and notify subscribers. It uses the getter and setter of Object.defineProperty of SE5 to implement internally.

Compile: Instruction parser (v-for, v-if...), its function is to scan and parse the instructions of each element node, replace the data according to the instruction template, and bind the corresponding update function

Watcher: Subscriber, as a bridge connecting Observer and Compile, can subscribe and receive notification of each attribute change, and execute the corresponding callback function bound by the instruction

Dep : Message subscriber, which maintains an array internally to collect subscribers (Watcher), data changes trigger the notify function, and then call the update method of the subscriber

Guess you like

Origin blog.csdn.net/weixin_43221910/article/details/123346592