In Vue 3 and the Composition API, you can watch for changes in props by using the watch function provided by Vue. This allows you to react to changes in props similar to how you might use watch in the Options API.

Here’s an example demonstrating how to watch for prop changes using the Composition API in Vue 3:

<template>
 <div>
   {{ myPropValue }}
 </div>
</template>

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

// Define props using the `defineProps` function
const props = defineProps({
 myProp: {
   type: String,
   required: true,
 },
});

// Create a ref to store the value of the prop
const myPropValue = ref(props.myProp);

// Watch for changes in props.myProp
watch(() => props.myProp, (newValue, oldValue) => {
 // React to prop changes
 console.log('Prop changed:', newValue);
 myPropValue.value = newValue; // Update the value in the ref if needed
});
</script>

 

Support On Demand!

Vue