search
HomeWeb Front-endVue.jsAn article explaining the principle of reactivity in Vue in detail
An article explaining the principle of reactivity in Vue in detailFeb 13, 2023 pm 07:30 PM
front endDesign Patternsvue.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

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

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()
        })
    }
}

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
}

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
    }
}

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
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
巧用CSS实现各种奇形怪状按钮(附代码)巧用CSS实现各种奇形怪状按钮(附代码)Jul 19, 2022 am 11:28 AM

本篇文章带大家看看怎么使用 CSS 轻松实现高频出现的各类奇形怪状按钮,希望对大家有所帮助!

5个常见的JavaScript内存错误5个常见的JavaScript内存错误Aug 25, 2022 am 10:27 AM

JavaScript 不提供任何内存管理操作。相反,内存由 JavaScript VM 通过内存回收过程管理,该过程称为垃圾收集。

实战:vscode中开发一个支持vue文件跳转到定义的插件实战:vscode中开发一个支持vue文件跳转到定义的插件Nov 16, 2022 pm 08:43 PM

vscode自身是支持vue文件组件跳转到定义的,但是支持的力度是非常弱的。我们在vue-cli的配置的下,可以写很多灵活的用法,这样可以提升我们的生产效率。但是正是这些灵活的写法,导致了vscode自身提供的功能无法支持跳转到文件定义。为了兼容这些灵活的写法,提高工作效率,所以写了一个vscode支持vue文件跳转到定义的插件。

Node.js 19正式发布,聊聊它的 6 大特性!Node.js 19正式发布,聊聊它的 6 大特性!Nov 16, 2022 pm 08:34 PM

Node 19已正式发布,下面本篇文章就来带大家详解了解一下Node.js 19的 6 大特性,希望对大家有所帮助!

浅析Vue3动态组件怎么进行异常处理浅析Vue3动态组件怎么进行异常处理Dec 02, 2022 pm 09:11 PM

Vue3动态组件怎么进行异常处理?下面本篇文章带大家聊聊Vue3 动态组件异常处理的方法,希望对大家有所帮助!

聊聊如何选择一个最好的Node.js Docker镜像?聊聊如何选择一个最好的Node.js Docker镜像?Dec 13, 2022 pm 08:00 PM

选择一个Node​的Docker镜像看起来像是一件小事,但是镜像的大小和潜在漏洞可能会对你的CI/CD流程和安全造成重大的影响。那我们如何选择一个最好Node.js Docker镜像呢?

聊聊Node.js中的 GC (垃圾回收)机制聊聊Node.js中的 GC (垃圾回收)机制Nov 29, 2022 pm 08:44 PM

Node.js 是如何做 GC (垃圾回收)的?下面本篇文章就来带大家了解一下。

【6大类】实用的前端处理文件的工具库,快来收藏吧!【6大类】实用的前端处理文件的工具库,快来收藏吧!Jul 15, 2022 pm 02:58 PM

本篇文章给大家整理和分享几个前端文件处理相关的实用工具库,共分成6大类一一介绍给大家,希望对大家有所帮助。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft