Blog>
Snippets

Watchers for Prop Changes

Implement a watcher to perform actions in a Vue.js 3 component when the value of a prop changes.
<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

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

// Define a prop with the name 'userAge'
const props = defineProps({
  userAge: Number
});

// Reactive reference to store the message
const message = ref('User age has not changed yet.');

// Watcher for prop 'userAge' changes
watch(() => props.userAge, (newAge, oldAge) => {
  // Perform an action whenever 'userAge' changes
  message.value = `User age changed from ${oldAge} to ${newAge}.`;
});
</script>

<style scoped>
h1 {
  color: #2c3e50;
}
</style>
This is a Vue.js 3 component using the Composition API. A template defines a simple structure displaying a message inside an <h1> element. Within the `<script setup>` block, a `watch` function is used to observe changes to the `userAge` prop. Whenever `userAge` changes, the message updates to reflect the new and old age values. The `<style scoped>` tag contains CSS to style the <h1> element.