- read

Vue Tip: Detect Changes in Values or Properties Using Watch

John Philip 47

Vue Tip: Detect Changes in Values or Properties Using Watch

Learn how to use Watch API to watch for changes in values

John Philip
JavaScript in Plain English
2 min read1 day ago

--

Identifying changes in values or properties is a frequent necessity in various applications. Within Vue.js, the watch API offers a valuable tool to observe changes and subsequently execute requisite actions in response.

Vuejs Pun for you

Why did the Vue component need glasses? To get a clearer ‘Vue’ of the DOM!

The watch property empowers us to establish watchers that monitor designated reactive properties or variables within our component. Upon changes to these properties, the associated watcher function activates, providing the means to manage these modifications as required.

Below is an example showcasing the use of the watch API in Vue.js.

<template>
<div>
<p>Guess a Number (Enter a number):</p>
<input v-model="guess" type="number" />
<p>{{ answer }}</p>
</div>
</template>

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

const guess = ref();
const answer = ref(''); // Initializing the answer as an empty string

// watch works directly on a ref
watch(guess, (newGuess, oldGuess) => {
if (newGuess !== '') {
if (newGuess % 2 === 0) {
answer.value = 'Your guess is an even number.';
} else {
answer.value = 'Your guess is an odd number.';
}
} else {
answer.value = ''; // Clear the answer when the guess is empty
}
});
</script>

This example demonstrates the practical usage of the watch API to monitor changes in reactive variables, enabling the execution of specific actions in response to these changes.

You can check out the code on Vuejs Playground.

Final thoughts

I’d be grateful if you could share this article with others. Your feedback is incredibly valuable, and a round of applause (👏) is a great way to show your appreciation!

If you have any questions or simply want to connect, please feel free to reach out to me on X via @amjohnphilip.

More reads