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.
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
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 that can 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
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:
The communication method between each part is:
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:
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, through Object.defineProperty ()
to hijack the setter
and getter
of 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 в основном выполняет две функции:
6.3 Зачем использовать виртуальный DOM
Введение в программированиеСвязанные рекомендации:
## Рекомендация по учебнику #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!