Home> Web Front-end> Vue.js> body text

Why use a front-end framework like vue.js?

青灯夜游
Release: 2020-11-30 13:36:10
Original
2465 people have browsed it

Vue can help create a more maintainable and testable code base; if you already have a ready-made server application, you can embed Vue as part of the application to bring richer functionality. Interactive experience; or if you want to implement more business logic on the front end, Vue's core library and its ecosystem can also meet your various needs.

Why use a front-end framework like vue.js?

The operating environment of this tutorial: Windows 7 system, Vue version 2.9.6. This method is suitable for all brands of computers.

1. What is Vue.js

Vue is a progressive JavaScript framework for building user interfaces.

2. Advantages of Vue.js

  • Small size: only 33k after compression;
  • is higher Operating efficiency: Based on virtual DOM, a technology that can perform various calculations through JavaScript in advance to calculate and optimize the final DOM operation. Since this DOM operation is a preprocessing operation and does not actually operate the DOM, it is called Virtual DOM;
  • Two-way data binding: allows developers to no longer have to operate DOM objects and devote more energy to business logic;
  • Rich ecology and low learning cost: on the market It has a large number of mature and stable UI frameworks and components based on vue.js, which can be used out of the box to achieve rapid development; it is friendly to beginners, easy to get started, and has a lot of learning materials;

3. Why use Vue.js

With the continuous development of front-end technology, front-end development can handle more and more businesses, and web pages are becoming more and more powerful and dynamic. ization, these advances are inseparable from JavaScript. In the current development, a lot of server-side code has been put into the browser for execution, which generates thousands of lines of JavaScript code, which are connected to various HTML and CSS files, but there is a lack of formal organizational form. This is also the reason why more and more front-end developers use JavaScript frameworks. Currently, the more popular front-end frameworks include Angular, Reac, Vue, etc.

Vue is a friendly, versatile and high-performance JavaScript framework thatcan help you create a more maintainable and testable code base.Vue is a progressive JavaScript framework, which means that if you already have a ready-made server application, you can embed Vue as part of the application to bring a richer interactive experience. Or if you want to implement more business logic on the front end, Vue's core library and its ecosystem can also meet your various needs.

Like other frameworks, Vue allows you to divide a web page into reusable components. Each component contains its own HTML, CSS, and JavaScript to render the corresponding place in the web page. If we build a large application, we may need to split things into separate components and files. Using Vue's command line tools makes it very simple to quickly initialize a real project.

vue init webpack my-project
Copy after login

We can even use Vue’s single-file components, which contain their own HTML, JavaScript, and scoped CSS or SCSS.

4. MVC, MVP, MVVM design patterns

MVC (Model-View-Controller) is one of the most common software architectures. It is widely used in the field of software development. MVC itself is relatively easy to understand, but it is not easy to explain clearly the MVP and MVVM derived from it.

4.1, MVC

MVC means that the software can be divided into three parts:

  • View: User Interface
  • Controller: Business logic
  • Model: Data storage

The communication method between each part is:

  • View sends instructions to Controller
  • After Controller completes the business logic, it requires Model to change state
  • Model sends new data to View, and the user gets feedback

And all communication is one-way, as shown in the following figure:

There are two ways to execute the MVC mode:

(1) Accept instructions through View and pass them to Controller

(2) Accept instructions directly through Controller

Actual A more flexible approach is often used in projects:

(1) The user can send instructions (DOM events) to the View, and then the View directly requests the Model to change the state;

(2) The user can also Send instructions directly to the Controller (changing the URL triggers the hashChange event), and then the Controller sends it to the view;

(3) The Controller is very thin and only plays a routing role, while the View is very thick, and the business logic is deployed in View, so some frameworks directly cancel the Controller, leaving only a Router.

as the picture shows:

4.2, MVP

MVP (Model-View-Presenter) evolved from the classic MVC. Mode provides data, View is responsible for display, and Presenter is responsible for logical processing.

There is a major difference between MVP and MVC:

  • In MVP, the View and the Model are not connected. The communication between them is carried out through the Presenter, and all interactions are Happens inside the Presenter (that is, the Controller in MVC); in MVC, the View will read data directly from the Model instead of through the Controller.
  • The communication between various parts in MVP is two-way, while the communication between various parts in MVC is one-way.
  • In MVP, View is very thin and does not deploy any business logic. It is called "Passive View" (Passive View), that is, it does not have any initiative, while Presenter is very thick and all logic is deployed there.

As shown in the figure:

4.3, MVVM

MVVM (Model-View- ViewModel), which is essentially an improved version of MVC, with a more detailed division of labor for View in MVC. ViewModel separates the view UI and business logic. It can take out the data of the Model and help process the business logic designed in the View due to the need to display content.

The MVVM mode is similar to the MVP mode. The only difference is that it uses two-way data binding (data-binding), that is, changes in the View are automatically reflected in the ViewModel, and vice versa. Likewise.

5. The principle of data-driven (two-way data binding)

What is data-driven

Data-driven is the biggest feature of Vue.js. In Vue, the so-called data-driven means that when the data changes, the user interface changes accordingly, and developers do not need to manually modify the DOM.

For example, when we click a button, the text of the element needs to perform a "yes/no" switching operation. In traditional jQuery, the process of page modification is usually: bind the event to the button, and then obtain The copy corresponds to the DOM object of the element, and finally the text value of the DOM object is modified according to the switch.

Vue implements data-driven

Vue implements two-way data binding mainly through data hijacking, in conjunction with the publisher-subscriber model, throughObject.defineProperty ()to hijack thesetterandgetterof each attribute, publish messages to subscribers when the data changes, and trigger the corresponding listening callback.

When a normal JavaScript object is passed to a Vue instance as its data option, Vue will iterate through its properties and convert them into getters/setters using Object.defineProperty. The getters/setters are not visible to the user, but internally they allow Vue to track dependencies and notify changes when properties are accessed and modified.

Vue's two-way data binding uses MVVM as the entrance to data binding, integrating Observer, Compile and Watcher. It uses Observer to monitor the data changes of its own Model, and uses Compile to parse and compile template instructions (vue used to parse {{}} template syntax), and finally use Watcher to build a communication bridge between Observer and Compile to achieve data changes -> view updates; view interactive changes (input) -> two-way binding of data model changes Effect.

Understanding of getters and setters

When printing out the attributes in the data object under the vue instance, each of its attributes has two corresponding get and set method. As the name suggests, get is the value method, and set is the assignment method. Under normal circumstances, value acquisition and assignment are done using obj.prop, but there is a problem with this. How do we know that the value of the object has changed?

We can understand get and set as functions. When we call the properties of the object, we will enter get.property(){...} and first determine whether the object has this property. If not, Then add a name attribute and assign a value to it; if there is a name attribute, then return the name attribute. You can think of get as a function that takes a value, and the return value of the function is the value it gets.

When assigning a value to an instance, it will enter set.property(val){...}. The formal parameter val is the value assigned to the property. Many things are done in this function, such as two-way binding. etc. Because this value must go through set every time, the value cannot be modified in other ways. In ES5, the object prototype has two properties,_defineGetter_and_defineSetter_, which are specially used to bind get and set to objects.

6. Virtual DOM

6.1 What is virtual DOM

Концепция Virtual DOM была представлена в Vue.js версии 2.0. Virtual DOM на самом деле представляет собой древовидную структуру, которая использует объекты JavaScript (узлы VNode) в качестве основы для моделирования структуры DOM. Эта древовидная структура содержит всю структуру DOM. информация. Проще говоря, Virtual DOM можно понимать как простой JS-объект, содержащий как минимум три атрибута: имя тега (tag), атрибуты (attrs) и объекты дочерних элементов (child). В разных платформах эти три свойства будут называться по-разному.

6.2 Роль виртуального DOM

Конечная цель виртуального DOM — отрисовка виртуальных узлов в представлении. Но если вы напрямую используете виртуальные узлы для перезаписи старых узлов, будет много ненужных операций DOM. Например, под тегом ul имеется много тегов li, и изменился только один из тегов li. В этом случае, если новый ul используется для замены старого ul, это приведет к потере производительности из-за этих ненужных DOM-операции.

Чтобы избежать ненужных операций с DOM, в процессе сопоставления виртуальных узлов с представлениями виртуальный DOM сравнивает виртуальные узлы со старыми виртуальными узлами, использованными при последнем рендеринге представления, чтобы определить узлы, которые действительно необходимо обновить. Для выполнения операций DOM, чтобы избежать работы с другими элементами DOM, которые не нуждаются в изменении.

На самом деле, виртуальный DOM в Vue.js в основном выполняет две функции:

  • Предоставляет виртуальный узел VNode, соответствующий реальному узлу DOM
  • Сравнить узел VNode с старый виртуальный узел oldVNode, а затем обновить представление

6.3 Зачем использовать виртуальный DOM

  • имеет кросс-платформенные преимущества, потому что Virtual DOM основан на объектах JavaScript и не полагается на реальную среду платформы, поэтому имеет кросс-платформенные возможности, такие как браузерные платформы, Weex, Node и т. д.
  • DOM работает медленно, а эффективность работы JS высока. Для повышения эффективности операцию сравнения DOM можно разместить на уровне JS. Поскольку скорость выполнения операций DOM намного медленнее, чем у операций JavaScript, большое количество операций DOM переносится в JavaScript, а алгоритм исправлений используется для расчета узлов, которые действительно необходимо обновить, тем самым минимизируя операции DOM, тем самым значительно улучшая производительность. Virtual DOM по сути создает кеш между JS и DOM. JS только управляет виртуальным DOM и, наконец, записывает изменения в реальный DOM.
  • Улучшите производительность рендеринга.Преимущество Virtual DOM заключается не в одной операции, а в возможности разумно и эффективно обновлять представление при больших и частых обновлениях данных.

Связанные рекомендации:

## 2020 Фронт-энды Vue Wabtions Сводка (с ответами)

## Рекомендация по учебнику #vue: последние 5 видеоуроков по vue.js в 2020 году.

Для получения дополнительных знаний о программировании посетите:
Введение в программирование

! !

The above is the detailed content of Why use a front-end framework like vue.js?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!