Ref and Reactive in Vue3: In-depth understanding of reactive programming

Preface

Vue 3 is a powerful front-end framework that introduces some exciting new features, the most notable of which refare reactive. These two APIs are the core of reactive programming in Vue 3, and this article will delve into their usage and differences.

What is reactive programming?

In Vue, reactive programming is a way of keeping data in sync with the UI. When the data changes, the UI automatically updates and vice versa. This mechanism greatly simplifies front-end development, allowing us to focus on data and user interface interaction without having to manually handle DOM updates.

Ref

refIt is a simple reactive API in Vue 3, used to create a reactive reference that wraps basic data types (complex types can also be wrapped, but the bottom layer is still implemented in a reactive way). Its main advantage is the ability to easily wrap basic data types and have a clear way of accessing and updating them.

Usage examples

import { ref } from 'vue';
 
const count = ref(0);
 
// 访问数据
console.log(count.value); // 输出 0
 
// 更新数据
count.value = 1;

In the above example, we first imported refthe function and then used it to create a countreactive reference called. We can access it like a normal variable, and when we update count, the associated UI updates automatically.

Advantage

  • Explicit data access syntax (.value)
  • Suitable for packaging basic data types, such as numbers, strings, etc.
  • Easier to read and understand, suitable for processing simple responsive data.

Reactive

Unlike ref, reactivewhich is a reactive reference used to create wrapper objects. This means it can be used to create reactive objects, not just basic data types. Its main advantage is more flexibility when dealing with complex data structures and the ability to wrap entire objects.

Usage examples

import { reactive } from 'vue';
 
const user = reactive({
  name: 'John',
  age: 30,
});
 
// 访问数据
console.log(user.name); // 输出 'John'
 
// 更新数据
user.age = 31;

In this example, we reactivecreate a userreactive object named using . userWe can access and update properties like ordinary object properties , and Vue will automatically track and process data changes.

Advantage

  • Suitable for wrapping complex objects and data structures, including nested objects.
  • No additional syntax ( .value) is required, properties are accessed directly.
  • More suitable for situations where multiple related properties are handled, such as form fields or component states.

The difference between Ref and Reactive

  1. Data type: refused to wrap basic data types (such as numbers, strings), and reactiveused to wrap objects.
  2. Access data: refWhen used, .valuedata needs to be accessed through , while reactivedirect access to properties is allowed.
  3. Packaging of data: refReturns a wrapped object, and reactivereturns a wrapped object.

The principles of Vue 3 responsive system

Vue 3’s reactive system is built on top of JavaScript Proxyobjects and Vue 2 Object.defineProperty, making it more flexible and powerful. Vue official documentation explains the principle of responsiveness

What is Proxy?

Proxy It is a built-in object in JavaScript that allows you to create a proxy object that can be used to intercept various operations on the target object, such as reading, writing, attribute retrieval, etc. Proxy Objects are often used to implement metaprogramming, which means that you can control and customize the behavior of the object.

Here are some Proxybasic concepts and usage about:

Create a Proxy object

To create an Proxyobject, you pass two parameters: the target object and a handler object. The handler object contains methods that define the behavior of the proxy object.

const target = { name: 'John' };
const handler = {
  get(target, key) {
    console.log(`Getting ${key} property`);
    return target[key];
  },
  set(target, key, value) {
    console.log(`Setting ${key} property to ${value}`);
    target[key] = value;
  }
};
 
const proxy = new Proxy(target, handler);
 

Interceptor method

ProxyThe handler object can contain various interceptor methods to control different operations. Some common interceptor methods include:

  • get(target, key, receiver): intercepts the read operation of the attribute.
  • set(target, key, value, receiver): Intercept the write operation of the attribute.
  • has(target, key): intercept the in operator.
  • deleteProperty(target, key): intercept delete operator.
    Etc... (Other methods are similar), these interceptor methods allow you to define the behavior of the proxy object to meet your needs.
Using Proxy objects

Once the object is created Proxy, you can use it like a normal object, but it will execute interceptor methods in the background.

console.log(proxy.name); // 会触发 get 拦截器,输出 "Getting name property"
proxy.age = 30; // 会触发 set 拦截器,输出 "Setting age property to 30"

In the above code, we create an Proxyobject proxythat intercepts targetread and write operations on the object.

Application examples

Proxy Objects are widely used and can be used to implement data binding, event systems, interception operations, etc. In some modern JavaScript frameworks and libraries, such as Vue 3 and Vuex, Proxythey are widely used to implement reactive systems, which can monitor changes in objects and automatically trigger corresponding update operations.

The principle of ref

refThe principle is relatively simple. It uses Proxyobjects to wrap basic data types such as numbers, strings, etc. When you use ref to create a reactive reference, Proxyyou actually create an object that intercepts read and write operations on the reference.

For example, when you access it count.value, Proxythe operation is captured and the actual value is returned. When you update count.value, Proxythis operation will also be captured and related dependency updates will be triggered, causing the related UI to be re-rendered.

The principle of reactive

reactiveThe principles involve more complex objects. It uses Proxyan object to wrap the entire object, not just the properties within it. This means you can add, remove, or modify properties on an object, and these operations will be Proxycaptured.

When you access or modify reactiveproperties of a wrapped object, Proxythese operations are captured and dependencies are automatically tracked. This means that when any properties change, Vue will know which components depend on those properties and will automatically update those components to reflect the latest data.

Implementation of responsive systems

Although the above is a brief explanation of the Vue 3 responsive system, it is in the Vue source code . , the implementation of this mechanism is more complicated. There is a lot of logic in the Vue source code for handling dependency tracking, dispatching updates and other operations to ensure synchronization between data and UI.
If you want to delve into Vue's source code, you can learn more about how it is implemented.

Summarize

refand reactiveare the core tools for reactive programming in Vue 3. They make synchronizing between data and UI easy. Based on your needs, choose the appropriate API to wrap your data for the best development experience. ref works with basic data types, while ref reactiveworks with objects. By using both flexibly, you can build dynamic Vue 3 applications more easily.

I hope this article has been helpful, provided you with a deep understanding refand reactivewill provide you with a solid foundation for reactive programming in Vue 3. Continue to explore the power of Vue 3 and create impressive web applications!

A set of Java/.Net+Vue low-code rapid development framework that separates front-end and back-end

The JNPF development platform is a simple, cross-platform rapid development framework based on Java Boot/.Net Core. The front-end and back-end encapsulate thousands of common classes for easy expansion; it integrates a code generator to support front-end and back-end business code generation, enabling rapid development and improving work efficiency; the framework integrates various commonly used classes such as forms, reports, charts, and large screens. Demo is easy to use directly; the back-end framework supports Vue2 and Vue3.
Many people have used it, it is a master of functions, and any information system can be developed based on it. The principle is to concretize certain recurring scenes and processes in the development process into components, APIs, and database interfaces to avoid reinventing the wheel. This greatly improves programmers' productivity. 
Application address: https://www.jnpfsoft.com/?csdn

Guess you like

Origin blog.csdn.net/wangonik_l/article/details/133314973