VueJS - Watch Property
Vue 3 - Watchers
Section titled “Vue 3 - Watchers”In Vue, watchers allow you to perform actions in response to changes in reactive data. This chapter demonstrates how to use watchers in Vue 3, using both the classic Options API and the modern Composition API.
Watchers are useful for performing asynchronous operations or complex logic when a specific piece of data changes.
Concept: Watching Data Changes
Section titled “Concept: Watching Data Changes”Imagine you have two input fields, one for kilometers and one for meters. When the value in one field changes, you want the other field to update automatically based on the conversion (1 km = 1000 m). Watchers are ideal for this scenario.
Example using Composition API (watch)
Section titled “Example using Composition API (watch)”The Composition API provides the watch function for creating watchers. This is the recommended approach for new Vue 3 applications.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Vue 3 Watchers (Composition API)</title> <script src="https://unpkg.com/vue@3"></script></head><body> <div id="app"> <h2>Kilometer / Meter Converter (Composition API)</h2> <label>Kilometers:</label> <input type="number" v-model="kilometers" /> <br/> <label>Meters:</label> <input type="number" v-model="meters" /> </div>
<script> const { createApp, ref, watch } = Vue;
const app = createApp({ setup() { const kilometers = ref(0); const meters = ref(0);
// Watch for changes in kilometers watch(kilometers, (newKilometers) => { // Avoid infinite loops by checking if the value is already correct if (newKilometers * 1000 !== meters.value) { meters.value = newKilometers * 1000; } });
// Watch for changes in meters watch(meters, (newMeters) => { if (newMeters / 1000 !== kilometers.value) { kilometers.value = newMeters / 1000; } });
return { kilometers, meters }; } });
app.mount('#app'); </script></body></html>In this Composition API example:
- We import
createApp,ref, andwatchfrom Vue. - We define
kilometersandmetersas reactive references usingref(0). - We use the
watchfunction. The first argument is the reactive source to watch (e.g.,kilometers). The second argument is a callback function that runs when the source changes. The callback receives the new value (newKilometers) and optionally the old value. - Inside the watcher callback, we update the other reactive variable (e.g., update
meterswhenkilometerschanges). - We added checks (
if (newKilometers * 1000 !== meters.value)) within the watchers to prevent infinite update loops that could occur if setting one value immediately triggered the other watcher, which then set the first value back.
Example using Options API (watch option)
Section titled “Example using Options API (watch option)”The Options API approach defines watchers within the watch option of the component.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Vue 3 Watchers (Options API)</title> <script src="https://unpkg.com/vue@3"></script></head><body> <div id="app-options"> <h2>Kilometer / Meter Converter (Options API)</h2> <label>Kilometers:</label> <input type="number" v-model="kilometers" /> <br/> <label>Meters:</label> <input type="number" v-model="meters" /> </div>
<script> const { createApp } = Vue;
const appOptions = createApp({ data() { return { kilometers: 0, meters: 0 }; }, watch: { // Watcher for the 'kilometers' data property kilometers(newValue) { // Avoid infinite loops if (newValue * 1000 !== this.meters) { this.meters = newValue * 1000; } }, // Watcher for the 'meters' data property meters(newValue) { if (newValue / 1000 !== this.kilometers) { this.kilometers = newValue / 1000; } } }, // Computed properties are often a better fit for simple dependencies // See the chapter on Computed Properties for comparison. computed: { // Example showing computed equivalent (might be simpler here) /* metersFromKm: { get() { return this.kilometers * 1000; }, set(val) { this.kilometers = val / 1000; } } */ } });
appOptions.mount('#app-options'); </script></body></html>In this Options API example:
kilometersandmetersare defined in thedataoption.- The
watchoption contains methods named after the data properties they watch (e.g.,kilometers(newValue)). - The logic inside the watcher methods is similar to the Composition API example, using
thisto access other data properties. - A commented-out
computedproperty example is included. For simple synchronous dependencies like this unit conversion, computed properties are often more concise and performant than watchers.
When to Use Watchers
Section titled “When to Use Watchers”- Fetching data asynchronously when a value (like an ID) changes.
- Performing complex logic or side effects that don’t directly map to a computed value.
- Throttling or debouncing actions based on rapid data changes (often combined with utility libraries like Lodash).
- Interacting with browser APIs or third-party libraries in response to state changes.
Remember to consider if a computed property might be a simpler and more appropriate solution before implementing a watch.
For more details, refer to the official Vue 3 documentation on Watchers.