Vue.js and MVVM small details

Vue.js and MVVM small details

MVVM is the abbreviation of Model-View-ViewModel, which is an architectural pattern based on front-end development. Its core is to provide two-way data binding between View and ViewModel, so that the state changes of ViewModel can be automatically passed to View, which is the so-called two-way data binding.

Vue.js is a Javascript library that provides MVVM-style two-way data binding, focusing on the View layer. Its core is the VM in MVVM, that is, ViewModel. ViewModel is responsible for connecting View and Model to ensure the consistency of view and data. This lightweight architecture makes front-end development more efficient and convenient.

1. Why does MVVM appear?

I came into contact with MVVM in 2015, which can be said to be the hottest year for MVVM. Before that, all I knew was MVC. I came into contact with MVC about 5 years ago, in 2011. At that time, I had just learned programming languages, Java, and the classic SSH framework in Java was used to build a standard MVC framework. To be honest, I have used MVC for so many years, but I still don’t have a deep understanding of it. It was not until I came into contact with Vue.js, studied the MVVM architecture concept, and then looked back at MVC that I felt a sense of sudden enlightenment~

MVC is the abbreviation of Model-View-Controller, which means a standard web application is composed of these three parts:

  • View is used to present data to the user in some way.
  • Model is actually data.
  • The Controller receives and processes requests from users and returns the Model to the user.

In the years before HTML5 became popular, MVC was OK as the best practice for Web applications. This was because the View layer of Web applications was relatively simple, and the data required by the front end could basically be processed by the back end. The View layer was mainly used for display. At that time, the Controller was advocated to handle complex business logic, so the View layer was relatively lightweight, which is the so-called thin client idea.

From 2010 to 2011, the concept of HTML5 was hotly discussed and sought after. In 2012, W3C officially announced that the HTML5 specification had been finalized. In 2013, when I first joined the company, I came into contact with the first HTML5 framework, Sench touch, which is an HTML5 framework for building mobile applications. It completely separates the front-end and back-end, and the front-end adopts the MVC architecture and is maintained as an independent project.

2. Why does the front end need to be engineered and use MVC?

Compared with HTML4, the biggest highlight of HTML5 is that it provides some very useful functions for mobile devices, making HTML5 capable of developing apps. The biggest advantage of developing apps with HTML5 is cross-platform, fast iteration and launch, saving labor costs and improving efficiency. Therefore, many companies have begun to transform traditional apps and gradually replace Native with H5. By 2015, most apps on the market were more or less embedded with H5 pages.

Since H5 is used to build the App, the View layer is not only responsible for simple data display, but also for managing complex data states and handling various operations on mobile devices. Therefore, the front end also needs to be engineered, and a framework similar to MVC is needed to manage these complex logics and make development more efficient. But the MVC here has changed a little bit:

  • View UI layout and display data.
  • Model manages data.
  • The Controller responds to user actions and updates the Model to the View.

This MVC architecture model seems OK for simple applications and is in line with the layered idea of ​​software architecture. But in fact, with the continuous development of H5, people hope that applications developed using H5 can be comparable to Native or close to the experience of native apps, so the complexity of front-end applications is different from the past. At this time, front-end development exposes three pain points:

  • Developers call the same DOM API a lot in their code, which is cumbersome and redundant, making the code difficult to maintain.
  • A large number of DOM operations reduce page rendering performance, slow down loading speed, and affect user experience.
  • When the Model changes frequently, developers need to actively update the View; when user operations cause the Model to change, developers also need to synchronize the changed data to the Model. This work is not only cumbersome, but also difficult to maintain complex and changeable data status.

In fact, the early emergence of jQuery was designed to enable the front-end to operate DOM more simply, but it only solved the first problem, and the other two problems always existed with the front-end.

3. The emergence of MVVM can solve the above three problems

MVVM consists of three parts: Model, View, and ViewModel. The Model layer represents the data model, and the business logic of data modification and operation can also be defined in the Model; View represents the UI component, which is responsible for converting the data model into UI for display. ViewModel is an object that synchronizes View and Model.

Under the MVVM architecture, there is no direct connection between View and Model. Instead, they interact through ViewModel. The interaction between Model and ViewModel is two-way, so changes in View data will be synchronized to the Model, and changes in Model data will be immediately reflected in the View.

ViewModel connects the View layer and the Model layer through two-way data binding, and the synchronization between View and Model is completely automatic and does not require human intervention. Therefore, developers only need to focus on business logic and do not need to manually operate DOM or worry about data status synchronization issues. Complex data status maintenance is completely managed by MVVM.

4. Vue.js Details

Vue.js can be said to be the best practice of MVVM architecture, focusing on ViewModel in MVVM. It not only achieves two-way data binding, but is also a relatively lightweight JS library with a simple API and is easy to use. There are ready-made tutorials on the basics of Vue online, so I will not go into details here. Let's take a brief look at some implementation details of two-way binding in Vue.js:

Vue.js uses Object.defineProperty's getters and setters combined with the observer pattern to implement data binding. When a plain Javascript object is passed to a Vue instance as its data option, Vue will traverse its properties and convert them to getters/setters using Object.defineProperty. Users cannot see getters/setters, but internally they allow Vue to track dependencies and notify changes when properties are accessed and modified.

  • Observer data listener can monitor all properties of data objects. If there is any change, it can get the latest value and notify the subscriber. It is implemented internally using the getter and setter of Object.defineProperty.
  • Compile instruction parser, which scans and parses the instructions of each element node, replaces data according to the instruction template, and binds the corresponding update function.
  • Watcher subscribers, as a bridge connecting Observer and Compile, can subscribe and receive notifications of each property change and execute the corresponding callback function bound to the instruction.
  • The Dep message subscriber maintains an array internally to collect subscribers (Watchers). Data changes trigger the notify function, which then calls the subscriber's update method.

As can be seen from the figure, when new Vue() is executed, Vue enters the initialization phase. On the one hand, Vue will traverse the attributes in the data option and use Object.defineProperty to convert them into getters/setters to implement the data change monitoring function; on the other hand, Vue's instruction compiler Compile scans and parses the instructions of the element node, initializes the view, and subscribes to Watcher to update the view. At this time, Wather will add itself to the message subscriber (Dep), and the initialization is completed.

When the data changes, the setter method in the Observer is triggered, and the setter immediately calls Dep.notify(). Dep starts to traverse all subscribers and calls the subscriber's update method. After receiving the notification, the subscriber updates the view accordingly.

The above content is my simple understanding and summary of MVVM and Vue.js after more than half a year of project practice. I hope it will be helpful to you!

<<:  A step-by-step guide to spam filtering with Python and Scikit-Learn

>>:  How do we do code review?

Recommend

This article will help you understand Zhihu algorithm!

We all know that self-media people attract user a...

The brand extension crisis of Microsoft, Xiaomi and LeTV

[[141229]] Microsoft, the world's largest sof...

Almost vertical! Do you dare to walk on this "ladder to heaven"?

A nearly vertical mountain road There are 11 &quo...

8 years after Steve Jobs' death, is Tim Cook a qualified Apple CEO?

October 5, 2019, coincided with the 70th annivers...

Windows 10 is frustrated. Can Cortana take on the future of Microsoft?

[[135660]] In March, Microsoft reached a cooperat...

How to descend from the sky scientifically?

When I was a kid, I watched "Kung Fu" a...

People who often eat midnight snacks must be careful about this problem~

Audit expert: Wu Xi Associate Chief Physician, De...