The perfect fit between data and view: the intertwined charm of Vue’s responsiveness

Front-end development engineer (main job), technical blogger (side job), passed CET6
Ashan and her cat_CSDN personal homepage
Senior topic writer at Niuke, creating a high-quality column “Essentials for Front-end Interviews” at Niuke
The contracted author of Lanqiao Cloud Class, the front-end and back-end practical courses “Vue.js and Egg.js Develop Enterprise-level Health Management Projects” and “Take you to fully master uni-app from entry to practice” have been launched on Lanqiao Cloud Class

Article directory

  • I. Introduction
    • A. Introduction to Vue.js
    • B. Vue’s responsiveness principle
  • II. Vue’s responsiveness principle
    • A. Data-driven view
      • 1. Introducing Vue’s declarative rendering
      • 2. Explain how Vue implements view updates through data binding
    • B. Data Hijacking and Listeners
      • 1. Introduce the data hijacking technology used in Vue
      • 2. Observer pattern and the role of listeners
    • C. Vue’s reactive objects
      • 1. How to create responsive objects
      • 2. Properties and methods of responsive objects

I. Introduction

A. Introduction to Vue.js

Introduction to Vue.js:

Vue.js (Vue for short) is a popular front-end JavaScript framework for building interactive user interfaces. It was created by Evan You in 2014 and open sourced in the same year. The goal of Vue.js is to provide an efficient and maintainable development experience through an easy-to-use API and a flexible architecture.

Here are some key features and highlights of Vue.js:

  1. Responsive data binding: Vue adopts a data-driven view model. Through Vue’s responsive system, when the data changes, the view will automatically update, which greatly simplifies the development process and improves development efficiency.

  2. Component-based development: Vue builds complex user interfaces through componentization. Components can be reused, making the code more modular and maintainable. Vue provides powerful componentization capabilities, including single-file components, inter-component communication, etc.

  3. Lightweight and high performance: Vue’s core library is very lightweight and has excellent performance. Vue uses virtual DOM and a sophisticated rendering mechanism to re-render only the parts that actually need to be updated, improving application performance.

  4. Ecosystem and community support: Vue has a large and active community, with many plug-ins and tools to choose from to meet the needs of different projects. At the same time, the Vue ecosystem provides rich documentation, examples, and tutorials so that novices can get started quickly.

  5. Progressive Framework: Vue is a progressive framework, which means that Vue features can be gradually adopted without having to undertake major changes all at once. It can be seamlessly integrated with existing projects or fully adopted in new projects.

The flexibility, ease of use, and high performance of Vue.js make it the framework of choice for more and more developers. It is suitable for building various types of projects such as single-page applications (SPA), multi-page applications (MPA), mobile applications, and cross-platform applications. Both beginners and experienced developers can benefit from Vue.js’s elegant and intuitive API and quickly build excellent user interfaces.

B. Vue’s responsiveness principle

Vue’s responsiveness principle is one of its core features, which makes the binding between data and views automated, efficient and flexible. Here’s a brief overview of Vue’s reactive principles:

  1. Responsive objects: In Vue, by passing ordinary JavaScript objects into the data option of the Vue instance, these objects will be converted into responsive objects. Vue will iterate through the properties of these objects and perform proxy hijacking on each property using the Object.defineProperty method.

  2. Data hijacking: Vue uses data hijacking technology to achieve responsiveness. It uses the Object.defineProperty method to add getters and setters to each property of the object to track property changes. When accessing a property, Vue will collect dependencies. When the value of the property changes, Vue will notify the relevant dependencies to update.

  3. Dependency tracking: In Vue, each property has a corresponding dependency. When a property is used in the view, Vue will collect the dependencies and establish an association between the property and the dependencies. This way, when properties change, Vue knows exactly which dependencies need to be updated.

  4. Responsive update: When the data changes, Vue will trigger the setter method and notify related dependencies to update. Through the optimization of virtual DOM and differentiation algorithm, Vue only re-renders the parts that need to be updated, improving performance and efficiency.

  5. Asynchronous update: In order to improve performance, Vue updates data changes asynchronously. In the same event loop, if the same property is modified multiple times, Vue will merge these modifications into one update to avoid unnecessary update operations.

Through this responsive mechanism, Vue can achieve automatic synchronization between data and views. When the data changes, the view automatically updates and vice versa. This allows developers to focus more on data changes and business logic without manually manipulating the DOM, greatly simplifying the interface development process.

II. Vue’s responsiveness principle

A. Data-driven view

1. Introducing Vue’s declarative rendering

Vue’s declarative rendering refers to the process of rendering data to the DOM through concise template syntax. Vue adopts HTML-like template syntax, allowing developers to describe desired results in a declarative manner without caring about the underlying operation details.

The following are the characteristics and working principles of Vue’s declarative rendering:

  1. Template syntax: Vue uses an HTML-based template syntax, and developers can directly insert data and expressions into the template. Vue’s template syntax allows you to use double curly braces {{}} to insert variables, and use directives to perform operations such as conditional rendering, looping, and event processing.

  2. Data binding: Vue can dynamically render data to the DOM through data binding in the template. When the data changes, the corresponding template part will automatically update to reflect the latest data status. This data binding mechanism allows developers to declaratively describe the relationship between application state and views.

  3. Responsive update: In Vue, when the data changes, the affected part of the view will automatically update. ThroughVue’s responsive system, views can reflect changes in data in a timely manner and remain synchronized with data. Developers do not need to manually manipulate the DOM, they only need to pay attention to data changes, and Vue will automatically handle the rendering and update process.

  4. Rendering Optimization: Vue achieves efficient rendering optimization through virtual DOM and differential update algorithms. When the data changes, Vue will compare the old and new virtual DOM and update only the parts that need to be changed instead of re-rendering the entire DOM tree. This optimization strategy greatly improves performance and rendering efficiency.

Through Vue’s declarative rendering, developers can focus more on describing the status and desired results of the application without manually managing DOM operations and updates. This declarative approach makes the code more concise and readable, improving development efficiency and maintainability.

2. Explain how Vue implements view updates through data binding

Vue implements automatic updating of views through data binding to ensure synchronization of views and data. Here’s how Vue works to implement view updates through data binding:

  1. Data hijacking: In Vue, data hijacking is achieved by converting ordinary JavaScript objects into responsive objects. Vue uses the Object.defineProperty method to convert the object’s properties into getters and setters. When the property value is obtained, the getter will be triggered, Vue will collect the current dependencies (observers), and then return the value of the property. When the property value is set, the setter will be triggered, and Vue will notify the corresponding observer to perform the update operation.

  2. Dependency collection: When the view in the template uses data, Vue will collect dependencies during the compilation phase. For each data access, Vue creates a watcher and associates it with the component currently being rendered. In this way, Vue knows which data is used and establishes dependencies between the data and the view.

  3. View update: Once the data changes and the setter is triggered, Vue will notify the corresponding observer to perform the update operation. These observers are responsible for updating the views associated with them and ensuring that the views and data are synchronized. Vue maintains an update queue internally. In the next event loop, Vue will sequentially execute the observer update operations in the queue.

  4. Virtual DOM and differential update: In order to improve performance and efficiency, Vue uses virtual DOM and differential update strategies. Every time the data is updated, Vue will generate a new virtual DOM tree and compare it with the last rendered virtual DOM tree to find the difference between the two. Then, only perform DOM operations on the difference parts, minimizing the modification of the actual DOM, thereby improving rendering efficiency.

Through data hijacking, dependency collection and observer mode, Vue realizes automatic binding and updating between data and views. Developers only need to pay attention to data changes without manually updating views. Vue will automatically respond to data changes and make corresponding view updates, ensuring the synchronization and consistency of data and views. This data binding mechanism allows developers to focus more on business logic and data processing, improving development efficiency and maintainability.

B. Data hijacking and listeners

1. Introducing the data hijacking technology used in Vue

When we use data hijacking technology in Vue, Vue will hijack (intercept) the properties of the object through the Object.defineProperty method, and add getters and setters on it. This hijacking process enables Vue to track the access and modification of properties and trigger corresponding update operations at the appropriate time to achieve the responsive nature of data.

Here is an example of data-hijacking techniques using Vue, involving a table containing names and ages:

<div id="app">
  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="person in persons" :key="person.id">
        <td>{<!-- -->{ person.name }}</td>
        <td>{<!-- -->{ person.age }}</td>
      </tr>
    </tbody>
  </table>
</div>
const app = new Vue({<!-- -->
  el: '#app',
  data() {<!-- -->
    return {<!-- -->
      persons: [
        {<!-- --> id: 1, name: 'John', age: 25 },
        {<!-- --> id: 2, name: 'Alice', age: 30 },
        {<!-- --> id: 3, name: 'Bob', age: 35 }
      ]
    };
  }
});

In the above code, we use Vue’s data option to define an array named persons, which contains objects containing names and ages. When we use the persons array in the template to traverse the display, Vue will hijack the properties of each object in it.

When we modify the attribute value of the object in the persons array, Vue will detect the modification of the attribute through data hijacking technology and trigger the corresponding view update. This means that if we modify the name or age attribute value of a person in the persons array, the data in the corresponding table will automatically Update, stay in sync with data.

In general, through data hijacking technology, Vue implements data hijacking and responsive tracking, ensuring that the view is automatically updated when the data is modified. This mechanism allows developers to handle the relationship between data and views in a more intuitive and natural way, improving code readability and development efficiency.

2. The role of observer mode and listener

Observer pattern and listener are both commonly used software design patterns to achieve loose coupling and event notification between components. They have the following different functions and ways of use:

Observer mode:

  • The Observer pattern is aPublish-Subscribe pattern used to implement a one-to-many relationship between objects, in which an observed object (called a topic or an observed object) maintains a set of observers Object that automatically notifies observer objects when the subject’s state changes.
  • Observed objects implement the observer pattern by adding, removing, and notifying observer objects. Observer objects need to implement an interface or provide a callback function so that the observers can be notified when their state changes.
  • The observer pattern can be used to implement event processing, message passing, GUI component communication and other scenarios, in which observer objects can subscribe to specific events or messages as needed.

Listener:

  • A listener is a lightweight mechanism used to detect state changes of an object and trigger corresponding operations or callback functions when the state meets specific conditions.
  • Listeners are usually associated with a specific property or event, and when the property value or event changes, the listener performs the appropriate action.
  • Listeners can be used to respond to user input, handle data changes, handle events, etc. Listeners can subscribe to specific property values or events of an object and execute specific logic when they change.

Summarize:
The Observer pattern is a general pattern for implementing one-to-many relationships between objects and is used to implement publish-subscribe and messaging mechanisms. The listener is a lightweight mechanism that is used to capture state changes of objects and take corresponding actions. Their usage focus and applicable scenarios are different. The observer pattern is usually used to implement more complex event and message communication, while the listener is mainly used to monitor changes in specific properties or events, and execute callback functions or events when they change. operate.

C. Vue’s responsive objects

1. How to create responsive objects

In Vue.js, you can create reactive objects using the data option of a Vue instance or Vue component. Here are some ways to create reactive objects:

  1. Declare object properties in the data option of a Vue instance or Vue component:
data() {<!-- -->
  return {<!-- -->
    myObject: {<!-- --> key: 'value' }
  };
}
  1. Use the Vue.observable() method to create a reactive object:
import {<!-- --> reactive } from 'vue';

const myObject = reactive({<!-- --> key: 'value' });
  1. Create a reactive reference (single value) using Vue’s ref function:
import {<!-- --> ref } from 'vue';

const myValue = ref('initial value');
  1. Use the computed attribute to calculate and generate responsive data:
import {<!-- --> computed } from 'vue';

const myObject = computed(() => {<!-- -->
  return {<!-- --> key: 'value' };
});

No matter which method you use, the objects you create are automatically responsive. This means that when an object’s properties change, the related components will automatically update to reflect those changes. For example, using the properties of a reactive object in a Vue template:

<template>
  <div>{<!-- -->{ myObject.key }}</div>
</template>

In the above code, when the key attribute of myObject changes, the related components will automatically update to display the latest value.

It should be noted that if you want to add new properties of the object to the already created responsive object, you need to use some special methods provided by Vue to implement responsiveness. For example, for the reactive object myObject that has been created, you can use the Vue.set() method or use the expand operator to create a new response formula object.

import {<!-- --> reactive, set } from 'vue';

const myObject = reactive({<!-- --> key: 'value' });

set(myObject, 'newKey', 'newValue'); // Add new properties to make them responsive
// or
const newObject = {<!-- --> ...myObject, newKey: 'newValue' }; // Create a new reactive object

Through the above methods, you can create and use responsive objects to automatically update the interface and reflect data changes.

2. Properties and methods of responsive objects

Reactive objects refer to objects used in Vue.js, which can achieve two-way binding and automatic updating of data. The following are some commonly used properties and methods of reactive objects:

Attributes:

  1. data: Attributes used to define responsive data. In the component, this data can be accessed through this.data.

method:

  1. Vue.set(object, key, value): Used to add properties to responsive objects or add responsiveness to existing properties. This is useful when adding new properties, as Vue.js cannot detect regular property additions or removals.

  2. Vue.delete(object, key): Used to delete properties from responsive objects. This will trigger the corresponding UI update.

  3. vm.$watch(expOrFn, callback, [options]): Used to listen for changes in responsive object properties. When the listened property changes, the callback function will be triggered.

  4. computed: Computed properties are properties calculated based on the state of the responsive object. Computed properties have a caching mechanism and will only be recalculated when the dependent data changes.

These properties and methods can help you effectively manage and operate reactive objects, achieving more flexible and efficient data binding and updates. Please note that these properties and methods are core features of Vue.js and are only available when using the Vue.js framework.