search
HomeWeb Front-endVue.jsDetailed explanation of the principle: the difference between reactive and ref in Vue3

This article will help you understand the most important APIs in vue3 - ref and reactive. Are you still confused about which one to use? If you want to use Vue3 well, let’s take a look

Detailed explanation of the principle: the difference between reactive and ref in Vue3

The responsiveness of vue2 is to hijack the getter and setter of the object through the Object.defineProperty method, collect dependencies in getter, and # Dependencies are triggered in ##setter, but this method has some shortcomings:

  • Because it is traversing recursively listening properties, when there are too many properties or the nesting level is too deep,

    Affects performance

  • Unable to monitor the object

    New attributes and deleted attributes, we can only monitor the attributes that exist in the object itself, so we designed$set and $delete

  • If you monitor an array, you cannot monitor the increase or decrease of array elements. You can only monitor the elements that can be accessed through subscripts. For existing properties in the array, because using

    Object.defineProperty to traverse the original elements of the monitoring array consumes too much performance, Vue gave up using Object.defineProperty to monitor the array, and The method of overriding the array prototype method is used to monitor the operations on the array data, and the $set and splice methods are used to update the array, $set and splice will call the overridden array method.

[Related recommendations:

vuejs video tutorial]

vue3 responsive implementation

Proxy object

In response to the shortcomings of Object.defineProperty, a new object - Proxy (object proxy) is introduced in ES6

Proxy object:

Used to create a proxy for an object, mainly used to change some default behaviors of the object. Proxy can be understood as setting up a layer of "interception" before the target object. External access to the object must first pass through this layer of interception. , thus providing a mechanism to filter and rewrite external access. The basic syntax is as follows:

/*
 * target: 目标对象
 * handler: 配置对象,用来定义拦截的行为
 * proxy: Proxy构造器的实例
 */
 var proxy = new Proxy(target,handler)
Intercept get, value operation

var proxy = new Proxy({}, {
  get: function(target, propKey) {
    return 35;
  }
});

proxy.time // 35
proxy.name // 35
proxy.title // 35
The operations that can be intercepted are:

FunctionOperationgetRead a valuesetWrite a valuehasin operator##deletePropertygetPrototypeOfsetPrototypeOfisExtensiblepreventExtensionsgetOwnPropertyDescriptordefinePropertyownKeysapplyconstruct

那么使用Proxy可以解决Vue2中的哪些问题,总结一下:

  • Proxy是对整个对象的代理,而Object.defineProperty只能代理某个属性。
  • 对象上新增属性,Proxy可以监听到,Object.defineProperty不能。
  • 数组新增修改,Proxy可以监听到,Object.defineProperty不能。
  • 若对象内部属性要全部递归代理,Proxy可以只在调用的时候递归,而Object.definePropery需要一次完成所有递归,Proxy相对更灵活,提高性能。

递归代理

var target = {
  a:1,
  b:{
    c:2,
    d:{e:3}
  }
}
var handler = {
  get:function(target, prop, receiver){
    console.log('触发get:',prop)
    return Reflect.get(target,prop)
  },
  set:function(target,key,value,receiver){
    console.log('触发set:',key,value)
    return Reflect.set(target,key,value,receiver)
  }
}
var proxy = new Proxy(target,handler)
 
proxy.b.d.e = 4 
// 输出  触发get:b , 由此可见Proxy仅代理了对象外层属性。

以上写法只代理了对象的外层属性,所以要想深层代理整个对象的所有属性,需要进行递归处理:

var target = {
  a:1,
  b:{
    c:2,
    d:{e:3}
  },
  f: {z: 3}
}
var handler = {
  get:function(target, prop, receiver){
    var val = Reflect.get(target,prop)
    console.log('触发get:',prop)
    if(val !== null && typeof val==='object') {
        return new Proxy(val,handler) // 代理内层属性
    }
    return Reflect.get(target,prop)
  },
  set:function(target,key,value,receiver){
    console.log('触发set:',key,value)
    return Reflect.set(target,key,value,receiver)
  }
}
var proxy = new Proxy(target,handler)
 
proxy.b.d.e = 4 
// 输出  触发get b,get d, get e

从递归代理可以看出,如果要代理对象的内部属性,Proxy可以只在属性被调用时去设置代理(惰性),访问了e,就仅递归代理b下面的属性,不会额外代理其他没有用到的深层属性,如z

关于 Reflect 的作用和意义

  • 规范语言内部方法的所属对象,不全都堆放在Object对象或Function等对象的原型上。如
Function.prototype.apply
Object.defineProperty
  • 修改某些Object方法的返回结果,让其变得更合理。比如,Object.defineProperty(obj, name, desc)在无法定义属性时,会抛出一个错误,而Reflect.defineProperty(obj, name, desc)则会返回false

  • Object操作都变成函数行为。某些Object操作是命令式,比如name in objdelete obj[name],而Reflect.has(obj, name)Reflect.deleteProperty(obj, name)让它们变成了函数行为。

  • Reflect对象的方法与Proxy对象的方法一一对应,只要是Proxy对象的方法,就能在Reflect对象上找到对应的方法。这就让Proxy对象可以方便地调用对应的Reflect方法,完成默认行为,作为修改行为的基础。也就是说,不管Proxy怎么修改默认行为,你总可以在Reflect上获取默认行为。

vue3的reativeref

Vue3 的 reactive 和 ref 正是借助了Proxy来实现。

reactive

作用:创建原始对象的响应式副本,即将「引用类型」数据转换为「响应式」数据

参数: reactive参数必须是对象或数组

reative函数实现:

// 判断是否为对象
const isObject = val => val !== null && typeof val === 'object';
// 判断key是否存在
const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);

export function reactive(target) {
    // 首先先判断是否为对象
    if (!isObject(target)) return target;

    const handler = {
        get(target, key, receiver) {
            console.log(`获取对象属性${key}值`)
            // 收集依赖 ...
            const result = Reflect.get(target, key, receiver)
            // 深度监听(惰性)
            if (isObject(result)) {
                return reactive(result);
            }
            return result;
        },

        set(target, key, value, receiver) {
            console.log(`设置对象属性${key}值`)

            // 首先先获取旧值
            const oldValue = Reflect.get(target, key, reactive)

            let result = Reflect.set(target, key, value, receiver);
            
            if (result && oldValue !== value) {
                // 更新操作 ...
            }
            return result
        },

        deleteProperty(target, key) {
            console.log(`删除对象属性${key}值`)

            // 先判断是否有key
            const hadKey = hasOwn(target, key)
            const result = Reflect.deleteProperty(target, key)

            if (hadKey && result) {
                // 更新操作 ...
            }

            return result
        },
        
        // 其他方法
        // ...
    }
    return new Proxy(target, handler)
}

const obj = { a: { b: { c: 6 } } };
const proxy = reactive(obj);

proxy.a.b.c = 77;

// 获取对象属性a值
// 获取对象属性b值
// 设置对象属性c值 77

至此,引用类型的对象我们已经可以把它转化成响应式对象了,Proxy对象只能代理引用类型的对象,对于基本数据类型如何实现响应式呢?

vue的解决方法是把基本数据类型变成一个对象:这个对象只有一个value属性,value属性的值就等于这个基本数据类型的值。然后,就可以用reative方法将这个对象,变成响应式的Proxy对象。

实际上就是: ref(0) --> reactive( { value:0 })

ref

作用:把基本类型的数据变为响应式数据。

参数:

1.基本数据类型

2.引用类型

3.DOM的ref属性值

ref 实现 Vue3 源码

export function ref(value?: unknown) {
  return createRef(value, false)
}

function createRef(rawValue: unknown, shallow: boolean) {
  if (isRef(rawValue)) {
    return rawValue
  }
  return new RefImpl(rawValue, shallow)
}

class RefImpl<t> {
  private _value: T
  private _rawValue: T

  public dep?: Dep = undefined
  public readonly __v_isRef = true

  constructor(value: T, public readonly __v_isShallow: boolean) {
    this._rawValue = __v_isShallow ? value : toRaw(value)
    this._value = __v_isShallow ? value : toReactive(value)
  }

  get value() {
    trackRefValue(this)
    return this._value
  }

  set value(newVal) {
    const useDirectValue =
      this.__v_isShallow || isShallow(newVal) || isReadonly(newVal)
    newVal = useDirectValue ? newVal : toRaw(newVal)
    if (hasChanged(newVal, this._rawValue)) {
      this._rawValue = newVal
      this._value = useDirectValue ? newVal : toReactive(newVal)
      triggerRefValue(this, newVal)
    }
  }
}</t>

大体思路就是,调用ref函数时会new 一个类,这个类监听了value属性的 get 和 set ,实现了在get中收集依赖,在set中触发依赖,而如果需要对传入参数深层监听的话,就会调用我们上面提到的reactive方法。

即:

ref(0); // 通过监听对象(类)的value属性实现响应式
ref({a: 6}); // 调用reactive方法对对象进行深度监听

根据上面的思路我们可以自己来简单实现下:

// 自定义ref
function ref(target) {
  const result = { // 这里在源码中体现为一个类 RefImpl
    _value: reactive(target), // target传给reactive方法做响应式处理,如果是对象的话就变成响应式
    get value () {
      return this._value
    },
    set value (val) {
      this._value = val
      console.log('set value 数据已更新, 去更新界面')
    }
  }
 
  return result
}
 
// 测试
const ref = ref(9);
ref.value = 6;

const ref = ref({a: 4});
ref.value.a = 6;

ref 方法包装的数据,需要使用.value 来访问,但在模板中不需要,Vue解析时会自动添加。

总结

  • reactive 将引用类型值变为响应式,使用Proxy实现
  • ref 可将基本类型和引用类型都变成响应式,通过监听类的value属性的getset实现,但是当传入的值为引用类型时实际上内部还是使用reactive方法进行的处理
  • 推荐基本类型使用ref,引用类型使用 reactive

(学习视频分享:web前端开发编程基础视频

Object.getPrototypeOf( )
Object.getPrototypeOf()
Object.setPrototypeOf()
Object.isExtensible()
Object.preventExtensions()
Object.getOwnPropertyDescriptor()
Object.defineProperty
Object.keys() Object.getOwnPropertyNames() and Object.getOwnPropertySymbols()
Call a function
new a function

The above is the detailed content of Detailed explanation of the principle: the difference between reactive and ref in Vue3. 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
Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment