vue 3 composition api watch
import { ref, watch } from 'vue';
export default {
setup() {
const count = ref(0);
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`);
});
function increment() {
count.value++;
}
return {
count,
increment,
};
},
};
Explanation:
Import Statements: Import the necessary functions (
ref
andwatch
) from the Vue library.Component Setup: Define the component using the Composition API by exporting the
setup()
function.Declare Reactive State: Create a reactive variable
count
usingref()
and initialize it with a value of0
.Watch for Changes: Use the
watch()
function to monitor changes to thecount
variable. Whencount
changes, the callback function receives thenewValue
andoldValue
, and logs the change to the console.Increment Function: Define an
increment()
function that increases the value ofcount
by one when called.Return Values: Return the
count
variable and theincrement()
function from thesetup()
function, making them accessible to the component template for rendering and interaction.