1. Listen for common types

ToRefs converts all attributes in a reactive object to individually reactive data

When the console prints in 🔔 Vue3, Proxy or REF indicates responsive data, and the changed data will be synchronized to the view.

🔔 ref can make primitive data reactive as well

import { ref, watch } from 'vue'
Copy the code
setup() {
    const number = ref(0)
    
    // Listen for the number variable and run the following callback function automatically if it changes
    watch(number, (newVal, oldVal) = > {
      console.log({ newVal, oldVal })
    })
    return { number }
  }
Copy the code
  • ToRef is a function that converts a property of a responsive object into a single responsive data with associated values.
  • ToRefs is a function that converts all properties of a reactive object into individual reactive data, making the object ordinary, and the values associated

2. Listen for responsive objects

  • Reactive is a function that defines a complex data type as reactive data.

💥 Reactive cannot make basic type data reactive

    // Define responsive object data
    const obj = reactive({
      name: 'elephant'.age: 18,})// Change the name of the function
    const btn = () = > {
      obj.name = 'the elephants'
      console.log('Has OBJ changed?', obj)
    }
Copy the code

3. Listen for multiple parameters

import { ref, watch } from 'vue'
setup() {
    const number = ref(0)
    const msg = ref('hello')
    
    // Listen for the number variable and run the following callback function automatically if it changes
    // Listen for [number, MSG]. If one of the data changes, the watch callback will be triggered
    watch([number, msg], (newVal, oldVal) = > {
      console.log({ newVal, oldVal })
    })
    return { number, msg }
  }
Copy the code

4. Deep listening and immediate execution

💥 {deep: true, immediate: true}

    // Define responsive object data
    const obj = reactive({
      name: 'elephant'.age: 18.cp: {
        name: 'flower'.age: 16,}})// Listen for reactive data defined by Reactive
    // newVal === oldVal
    Reactive () by default is deep listening and can listen to changes in all child properties
    
    // Note:
    // 💥 If the value of the listening attribute is primitive data, you need to write the function to return the attribute to listen

    watch(
      () = > obj.cp,
      val= > {
        console.log('Little elephant has found CP and wants to give red envelopes', val)
      },
      { deep: true , immediate: true})Copy the code