[vue3] Responsive proxy vs original object

It is worth noting that reactive() returns a Proxy of the original object, which is not equal to the original object:

const raw = {
    
    }
const proxy = reactive(raw)

// 代理对象和原始对象不是全等的
console.log(proxy === raw) // false

Only proxy objects are reactive, changes to the original object will not trigger an update. Therefore, the best practice when using Vue's reactive system is to only use proxy versions of the objects you declare.

<script setup>
  import {
      
       reactive } from 'vue'

  const raw = ['foo']
  const reacRaw = reactive(raw)

  function changeOrigin() {
      
      
    raw.push('bar')
  }
  function changeReac() {
      
      
    reacRaw.push('baz') 
  }
</script>

<template>
  <button @click="changeOrigin">
    {
   
   { raw }}
  </button>
  <br>
  <button @click = "changeReac">
    {
   
   { reacRaw }}
  </button>
</template>

Insert image description here
Drill Ground: Drill Ground-vuejs.org

To ensure consistent access to the proxy, calling reactive() on the same original object will always return the same proxy object, while calling reactive() on an existing proxy object will return itself:

// 在同一个对象上调用 reactive() 会返回相同的代理
console.log(reactive(raw) === proxy) // true

// 在一个代理上调用 reactive() 会返回它自己
console.log(reactive(proxy) === proxy) // true

This rule also applies to nested objects. Relying on deep reactivity, nested objects within reactive objects are still proxies:

const proxy = reactive({
    
    })

const raw = {
    
    }
proxy.nested = raw

console.log(proxy.nested === raw) // false

Guess you like

Origin blog.csdn.net/weixin_43361722/article/details/129811558