[Introduction to Vue] MVVM data two-way binding and the life cycle of Vue

Table of Contents

1. Introduction to Vue

1.1 What is Vue?

1.2 Advantages of Vue

1.3 The difference between libraries and frameworks

2. Getting started with Vue

2.1 MVVM (two-way data binding)

2.2 BootCDN (acceleration service)

3. Vue instance

3.1 Vue development example

3.2 Two-way data binding

3.3 Vue life cycle hooks


1. Introduction to Vue

1.1 What is Vue?

Vue is a progressive JavaScript framework for building user interfaces. “Progressive” means that Vue’s design philosophy is to gradually enhance the functionality and complexity of the application, rather than introducing all features at once. This allows developers to selectively use different features and functions of Vue according to project needs.

1.2 Advantages of Vue

Vue has many practical advantages, here are some of them:

  1. Easy to learn and use: Vue has a simple and intuitive API and clear documentation, allowing beginners to get started quickly. Its syntax and concepts are very similar to traditional HTML, CSS and JavaScript, reducing the learning curve.

  2. Progressive development: Vue’s progressive features allow developers to selectively use Vue’s different features and functions according to project needs. This flexibility makes Vue suitable for projects of all sizes and complexity.

  3. Responsive data binding: Vue’s responsive data binding mechanism keeps data and views synchronized. When data changes, related DOM elements are automatically updated. This simplifies the development process and reduces the workload of manually manipulating the DOM.

  4. Component-based development: Vue encourages developers to split applications into multiple reusable components, each with its own template, logic and style. Component-based development improves the maintainability and reusability of code, and also makes team collaboration more efficient.

  5. Virtual DOM and high performance: Vue uses virtual DOM to improve performance. By comparing the differences in the virtual DOM, Vue only updates the parts that need to be updated, reducing operations on the real DOM and improving performance. In addition, Vue also has optimization strategies such as asynchronous rendering and component-level lazy loading, which further improves application performance.

  6. Ecosystem and plugin support: Vue has a huge ecosystem with many third-party libraries and plugins to choose from. These libraries and plug-ins can help developers solve various problems and improve development efficiency.

Vue has the advantages of easy to learn and use, strong flexibility, superior performance, and high maintainability, making it an ideal choice for building modern web applications. As a software engineer, I often use Vue to develop front-end applications, and I continue to learn and explore Vue’s latest technologies and best practices to provide high-quality user interfaces.

1.3 The differences between libraries and frameworks

  1. Library: Such as: (the most typical one in js is jQuery)

    • A library is a collection of reusable code that solves a specific problem or provides specific functionality. It usually contains a series of functions, classes, methods or tools, and developers can selectively use the functions in the library according to their needs.
    • The way to use the library is to call it actively. Developers introduce the library into their own code and call the functions or methods in the library as needed to complete specific tasks.
    • Libraries usually have a small size and only provide specific functions. Developers can choose the appropriate library to build applications according to their own needs.
  2. Framework:

    • A framework is the basis of a software architecture that provides a set of solutions and tools for developing specific types of applications. It defines the structure, specifications and workflow of the application, and developers need to develop according to the rules of the framework.
    • The way the framework is used is to call it passively. Developers write the application code and embed it into the framework, and the framework controls the execution process of the application.
    • Frameworks usually have a large volume and provide a complete development environment and a series of functional modules. Developers can quickly develop based on the framework and reduce repetitive work.

2. Getting Started with Vue

2.1 MVVM (two-way data binding)

Before using it, let’s first understand what is MVVM? , simply speaking, it is a better UI mode solution. MVVM can automatically synchronize data in both directions through two-way data binding.

MVVM M-V-VM
M

modeldata model

V

viewview

VM ViewModel view model, which associates Model and view is ViewModel. viewModel is responsible for synchronizing Model data to View for display. , and is also responsible for synchronizing View modifications back to Model

1) V (modify data) -> M Submit the data of the view layer to the back-end server through events (front-end to back-end)
$(‘#btn_login’).click(function(){
Pass the data in the page to the back-end server in json format through ajax
});

2) M (modify data) -> V displays the backend data (JSON) in the view layer through assignment (backend to frontend)
Call the back-end data interface through ajax to render the returned JSON data to the page.
$(‘#book_name’).val(“xxx”);

Compared with the MVC pattern, the MVVM model is a more modern architectural pattern. It introduces a new component based on the MVC pattern: the view model (ViewModel). The MVVM pattern divides the application into four main components: Model, View, ViewModel and Data Binding. The model is responsible for processing data and business logic, the view is responsible for displaying the user interface, and the view model acts as an intermediary between the model and the view, responsible for processing the state and behavior of the view. The data binding mechanism makes data synchronization between views and view models simpler and more automated. The advantage of the MVVM pattern is that it separates views and business logic, making the code easier to maintain and test, and provides a better user interface interaction experience through the data binding mechanism.

2.2 BootCDN (acceleration service)

Official website: BootCDN – Bootstrap Chinese website open source project free CDN acceleration service

The full name of CDN is Content Delivery Network, which is a content distribution network. CDN is a content distribution network built on the network. It relies on edge servers deployed in various places and enables users to use load balancing, content distribution, scheduling and other functional modules of the central platform. Obtain the required content nearby, reduce network congestion, and improve user access response speed and hit rate.

  1. The key technologies of CDN mainly include content storage and distribution technology.
  2. CDN acceleration mainly accelerates static resources, such as images and media uploaded on the website, as well as some imported JS, CSS and other files.
  3. CDN acceleration relies on various network nodes. For example, 100 CDN servers are distributed across the country. When accessed from Shanghai, resources will be returned from the nearest node. This is the core.
  4. The CDN server realizes resource reserve by caching or actively crawling the content of the main server.
  5. The basic principle of CDN: distribute the content of the origin site to the node closest to the user, so that the user can obtain the required content nearby and improve the response speed and success rate of user access.
  6. CDN is deployed in the network provider’s computer room. When users request network services, they can obtain data from the nearest network provider’s computer room.

The biggest advantage is that it allows users to access resources nearby, so that we do not need to download the required tools or libraries, which facilitates development and reduces project resources.

Disadvantages of using CDN:
After talking about the advantages, let’s talk about the disadvantages. For websites that do not use CDN, if it collapses, I will sit still. For a small number of websites that rely on CDN for resources, it may only affect the experience, such as page display, js events, etc., but for websites that rely heavily on CDN, it can only be said that they will all die together. . .

3. Vue instance

3.1 Vue development example

Vue has two development methods, one is direct page development and the other is engineering-level development. This example uses the direct page development method.

Note:

1. Every Vue application starts by creating a new Vue instance using the Vue constructor.
2. You need to specify a content management area for Vue. Usually we also call it the boundary, which means that all our subsequent changes will be within the specified div, and the outside of the div will be useless.
3. Double curly braces are called interpolation

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Getting started with Vue</title>
<!-- 1. Import tool -->
<script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<!-- 2. Define the boundary managed by vue, which has one and only one root node -->
<div id="xw">
<h1>{<!-- -->{msg}}</h1>
</div>
<script type="text/javascript">
/* 3. Build a vue instance and bind the boundary */
newVue({
el:"#xw",
data(){
return{
msg:'hello Serena',
}
}
})
</script>
</body>
</html>

3.2 Two-way data binding

  1. vue directive: refers to special attributes with the “v-” prefix
  2. The methods of the vue instance are used to define the functions used by interactive events. There is no restriction on the function name.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Getting started with Vue</title>
<script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div id="xw">
<h1>{<!-- -->{msg}}</h1>
<p>
<input v-model="msg" />
                <!-- v-on: (can also be replaced by @) -->
<button v-on:click="getMsg">Get the content of the input box</button>
\t\t\t</p>
</div>
<script type="text/javascript">
newVue({
el: "#xw",
data() {
return {
msg: '123',
}
},
methods: {
getMsg() {
alert(this.msg);
}
}
})
</script>
</body>
</html>

Note:

  • Changes in data will cause changes in the DOM, and changes in the DOM will also cause changes in the data.
  • Only properties present in data when the instance is created are reactive
  • Create two-way data binding on form control elements using the v-model directive
  • this points to the current Vue instance in the methods attribute method
  • The console object can use printf-style placeholders. Only supports four types: characters (%s), integers (%d or %i), floating point numbers (%f) and objects (%o)
  • Vue instances also expose some useful instance properties and methods. They are all prefixed with $ to distinguish them from user-defined properties

3.3 Vue life cycle hook

Vue lifecycle hooks are callback functions that are executed at different stages of the Vue instance. These hook functions allow us to execute custom logic at specific lifecycle stages for initialization, update, and destruction operations at different stages of the application.

The following is Vue’s life cycle hook function:

  1. beforeCreate: Called before the instance is created, when data observation and event configuration have not yet been completed.

  2. created: Called after the instance is created. At this time, data observation has been completed but has not yet been mounted on the DOM.

  3. beforeMount: Called before the instance is mounted to the DOM.

  4. mounted: Called after the instance is mounted to the DOM. At this time, the DOM elements can be accessed.

  5. beforeUpdate: Called before data is updated, before the virtual DOM is re-rendered and patched.

  6. updated: Called after the data is updated, after the virtual DOM is re-rendered and patched.

  7. beforeDestroy: Called before the instance is destroyed, while the instance is still fully available.

  8. destroyed: Called after the instance is destroyed. At this time, the instance has been destroyed and all event listeners and sub-instances have been removed.

In addition to these commonly used life cycle hook functions, Vue also provides some other hook functions, such as activated and deactivated, to handle the activation and deactivation of keep-alive components.

Vue life cycle
Vue life cycle

Example: