Preface
Vue 3 is a powerful front-end framework that introduces some exciting new features, the most notable of which ref
are 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
ref
It 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 ref
the function and then used it to create a count
reactive 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
, reactive
which 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 reactive
create a user
reactive object named using . user
We 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
- Data type:
ref
used to wrap basic data types (such as numbers, strings), andreactive
used to wrap objects. - Access data:
ref
When used,.value
data needs to be accessed through , whilereactive
direct access to properties is allowed. - Packaging of data:
ref
Returns a wrapped object, andreactive
returns a wrapped object.
The principles of Vue 3 responsive system
Vue 3’s reactive system is built on top of JavaScript Proxy
objects 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 Proxy
basic concepts and usage about:
Create a Proxy object
To create an Proxy
object, 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
Proxy
The 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 Proxy
object proxy
that intercepts target
read 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, Proxy
they are widely used to implement reactive systems, which can monitor changes in objects and automatically trigger corresponding update operations.
The principle of ref
ref
The principle is relatively simple. It uses Proxy
objects to wrap basic data types such as numbers, strings, etc. When you use ref to create a reactive reference, Proxy
you actually create an object that intercepts read and write operations on the reference.
For example, when you access it count.value
, Proxy
the operation is captured and the actual value is returned. When you update count.value
, Proxy
this operation will also be captured and related dependency updates will be triggered, causing the related UI to be re-rendered.
The principle of reactive
reactive
The principles involve more complex objects. It uses Proxy
an 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 Proxy
captured.
When you access or modify reactive
properties of a wrapped object, Proxy
these 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
ref
and reactive
are 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 reactive
works 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 ref
and reactive
will 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!