Table of Contents
Analyze reactive
Vue2’s Object.defineProperty
Vue3’s Proxy
Home Web Front-end Vue.js An article explaining the principle of reactivity in Vue in detail

An article explaining the principle of reactivity in Vue in detail

Feb 13, 2023 pm 07:30 PM
front end Design Patterns vue.js

This article will help you learn Vue and gain an in-depth understanding of the responsiveness principles in Vue. I hope it will be helpful to you!

An article explaining the principle of reactivity in Vue in detail

This article commemorates the passing of responsive syntax sugar

Without further ado, let’s get straight to the point. Responsiveness is Applications in daily development are very common. Here is a simple example:

let a=3
let b=a*10
console.log(b)//30
a=4
console.log(b)//40
Copy after login

At this time we want b=4*10, which is obviously not possible, even if we add a ## in front #var will only variable promotion, the value we give will not be promoted.

At this time, the role of responsiveness is reflected:

import { reactive } from 'vue'

let state = reactive({ a: 3 })
let b = computed(() => state.a * 10)
console.log(b.value) // 30
state.a = 4
console.log(b.value) // 40
Copy after login

Only a simple

responsive API can achieve the effect of tracking changes. [Related recommendations: vuejs video tutorial, web front-end development]

Analyze reactive

In fact, Vue3

reactive is essentially a publish-subscribe model

by creating a dependency graph to track data dependencies. A dependency graph is a graph that describes which data depends on which data. When the data changes, Vue 3's

reactive system will automatically trigger an update of the view. This is because it tracks data changes in the dependency graph and achieves this by associating it with updates to the view

Here I list the code demonstrated by Youda in Vue Master as a simple example :

class Dep{
    constructor(value){
        this.subscribers=new Set()
        this._value=value
    }
    get value(){
        this.depend()
        return this._value
    }
    set value(newValue){
        this._value=newValue
        this.notify()
    }
    depend(){
        if(activeEffect){
            this.subscribers.add(activeEffect)
        }
    }
    notify(){
        this.subscribers.forEach(effect=>{
            effect()
        })
    }
}
Copy after login

Let’s analyze this code:

    Define a
  • subscribe attribute as a subscriber list to store all Subscriber information
  • depend function is used to manage dependency relationships, that is, the variable
  • notify function on which the subscriber depends is used as a notification The value of this variable has changed for all subscribers
When the value of the variable changes, it can automatically notify all subscribers to update

Vue2’s Object.defineProperty

In fact, in the Vue2 period, responsiveness was implemented by

Object.defineProperty, but in Vue3 it was switched to Proxy, let’s wait and see the reason combined with the actual code; let’s first take a look at how Vue2 is implemented:

function reactive(raw){
    Object.keys(raw).forEach(ket=>{
        const dep=new Dep()
        let value=raw[key]
        
        Object.definProperty(raw,key,{
            get(){
                dep.depend()
                return value
            },
            //当属性发生
            set(newValue){
                value=newValue
                dep.notify()
            }
        })
    })
    //这时候返回的原始对象已经具有响应性
    return raw
}
Copy after login

Such a simple reactive API is implemented

But the shortcomings here are obvious:

In Vue 2.x, the object passed in will be directly changed by Vue.observable But in Vue3, it is Will return a responsive proxy, but directly changing the source object is still unresponsive

This leads to:

    When When we
  • add or delete the properties of the object, Vue2's responsiveness cannot be detected. Since Vue will perform getter/setter conversion on the property when initializing the instance, the property must be in data Only when it exists on the object can Vue convert it into a responsive
  • Unable to detect the
  • subscript and length changes of the array
Of course, this is a historical limitation. At that time, ES5 could only choose

Object.definProperty, but in the ES6 version, there are more Proxy. At this time, Vue’s response The formula has been upgraded

Vue3’s Proxy

Vue3 uses

Proxy to monitor data changes. Compared with Vue2, it not only solves In addition to the above problems, there are also these advantages:

    No need to use
  • vue.$set to trigger reactivity, which makes the code look more Introduction
  • Comprehensive array change detection, eliminating invalid boundary conditions in Vue2
  • Reduces the amount of responsive code written in Vue3, which makes our development more convenient
Let's take a look at what the actual code looks like:

const reactiveHandles={
    get(target,key,receiver){
        const dep=getDep(target,key)
        dep.depend()
        return Reflect.get(target,key,receiver)
    },
    set(target,key,value,receiver){
        const dep=getDep(target,key)
        const result=Reflect.set(target,key,value,receiver)
        dep.notify()
        return result
    }
}
Copy after login
The responsive way is to

collect dependencies on objects. The essence of Vue3 responsiveness

ref

There is a sentence in the official documentation: The various limitations of

reactive() are ultimately because JavaScript cannot function The "reference" mechanism for all value types, and the limitation of reactive is:

    can only handle observable data structures, such as arrays and objects; and unobservable data structures , such as primitive data types, they cannot be monitored
  • Can only process data defined in the component where it is located, and cannot process global variables
And this time it is needed

ref is here, ref was born for basic data type, which makes up for the shortcomings of reactive. To put it simply, ref is more suitable for simple single variable values ​​(but in actual development Most of the time it’s just refs. Hahahaha

By the way, it’s a pity that the responsive syntax sugar proposal was cancelled

(Learning video sharing: vuejs introductory tutorial, Basic programming video)

The above is the detailed content of An article explaining the principle of reactivity in Vue in detail. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

Is Vue used for frontend or backend? Is Vue used for frontend or backend? Apr 03, 2025 am 12:07 AM

Vue.js is mainly used for front-end development. 1) It is a lightweight and flexible JavaScript framework focused on building user interfaces and single-page applications. 2) The core of Vue.js is its responsive data system, and the view is automatically updated when the data changes. 3) It supports component development, and the UI can be split into independent and reusable components.

Is vue.js hard to learn? Is vue.js hard to learn? Apr 04, 2025 am 12:02 AM

Vue.js is not difficult to learn, especially for developers with a JavaScript foundation. 1) Its progressive design and responsive system simplify the development process. 2) Component-based development makes code management more efficient. 3) The usage examples show basic and advanced usage. 4) Common errors can be debugged through VueDevtools. 5) Performance optimization and best practices, such as using v-if/v-show and key attributes, can improve application efficiency.

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

Application of design patterns in Guice framework Application of design patterns in Guice framework Jun 02, 2024 pm 10:49 PM

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

What are the advantages and disadvantages of using design patterns in java framework? What are the advantages and disadvantages of using design patterns in java framework? Jun 01, 2024 pm 02:13 PM

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

See all articles