VUE3-watch listens to the ref package object

VUE3-watch listens to the ref package object

Review Responsive

  • ref(100)===> RefImpl object, reference object (implemented using object.defineProperty). This reference object can be monitored.
  • reactive===> Proxy object, proxy object (implemented using Proxy), can monitor this proxy object.
  • ref({})===> RefImpl object, reference object (using object.defineProperty + Proxy), can monitor proxy objects and reference objects

key point

Watch listening is to listen to responsive objects, that is, RefImpl objects and Proxy objects. If it is not responsive, you need to use a function form.

code

<template>
  <div>计数器:{
   
   {counterRefImpl}}</div>
  <button @click="counterRefImpl++">点我加1</button>
  <div>计数器2:{
   
   {data.a.b.c.counter}}</div>
  <button @click="data.a.b.c.counter++">点我加1</button>
  <div>计数器3:{
   
   {data.counter}}</div>
  <button @click="data.counter++">点我加1</button>
</template>

<script>
  import {
      
      
    ref,
    watch
  } from 'vue'
  export default {
      
      
    setup() {
      
      
      let counterRefImpl = ref(1)
      let data = ref({
      
      
        counter: 2,
        a: {
      
      
          b: {
      
      
            c: {
      
      
              counter: 1
            }
          }
        }
      })

      // 监视data
      // data.value为一个代理对象
      // oldValue 又是拿不到的
      // deep配置无效。
      watch(data.value, (newValue, oldValue) => {
      
      
        console.log(newValue, oldValue);
      }, {
      
      
        deep: false
      })

      // data是一个RefImpl对象。支持deep配置的。默认是没有开启深度监视的
      // watch(data, (newValue, oldValue) => {
      
      
      //   console.log(newValue, oldValue);
      // }, {deep: true})

      // watch
      // 错误的, 因为counterRefImpl.value 为一个值,不是一个响应式对象
      // watch(data.value.counter, (newValue, oldValue) => {})
      // watch(counterRefImpl.value, (newValue, oldValue) => {})

      console.log(counterRefImpl);
      // 可以监视到的,使用函数形式
      watch(() => data.value.counter, (newValue, oldValue) => {
      
      
        console.log(newValue, oldValue);
      })
      watch(() => counterRefImpl.value, (newValue, oldValue) => {
      
      
        console.log(newValue, oldValue);
      })

      return {
      
      
        data,
        counterRefImpl
      }
    }
  }
</script>

[External link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-9QgtFg3Q-1689761730559)(https://gitee.com/zhang_luwei/image-resources/raw/master/image /1689647918250.jpg)]

Involving content

VUE3、ref、RefImpl、Proxy、watch

Guess you like

Origin blog.csdn.net/MCCLS/article/details/131815277