[vue3] In vue3, combined API, watch how to monitor props data

In the combined API of Vue 3, you can use the watch function to monitor data changes in props.

The first parameter of the watch function can be a function or a responsive data source, such as ref, reactive, etc.

Use a function as first argument:

If the first argument is a function, then the function will be called every time the dependency changes and return the value to listen for. This way, when dependencies change, the watch function will automatically rerun.

<script>
import {
    
     watch, ref } from 'vue';

export default {
    
    
  props: {
    
    
    propValue: {
    
    
      type: String,
      required: true
    }
  },
  setup(props) {
    
    
    const propValue = ref(props.propValue);

    watch(() => propValue.value, (newValue, oldValue) => {
    
    
      console.log('Props Value changed:', newValue);
    });

    return {
    
    
      propValue
    };
  }
};
</script>

Use a reactive data source as the first parameter:

If the first parameter is a reactive data source, then the watch function will directly monitor changes in the data source and execute the callback function every time it changes.

<script>
import {
    
     watch, ref } from 'vue';

export default {
    
    
  props: {
    
    
    propValue: {
    
    
      type: String,
      required: true
    }
  },
  setup(props) {
    
    
    const propValue = ref(props.propValue);

    watch(propValue, (newValue, oldValue) => {
    
    
      console.log('Props Value changed:', newValue);
    });

    return {
    
    
      propValue
    };
  }
};
</script>

The difference between the two methods:

  1. function as first argument:
  • The function is called every time the dependency changes and returns the value to listen for.
  • When dependencies change, the watch function automatically reruns the function and compares the returned value with the previous value to determine whether to execute the callback function.
  • It is suitable for returning the value to be monitored after calculation or processing logic, such as obtaining the data that needs to be monitored through calculated properties or other functions.
  1. Reactive data source as first parameter:
  • Directly monitor changes in reactive data sources without having to manually obtain the value to be monitored in the callback function.
  • When the reactive data source changes, the watch function will directly execute the callback function.
  • Suitable for directly monitoring changes in responsive data sources, such as ref, reactive, etc.

Guess you like

Origin blog.csdn.net/weixin_40887836/article/details/132513110