In Vue 3, ref and reactive are two core APIs for creating reactive data. We can monitor changes in these reactive data using the watch function. watch is an API provided by Vue 3 for reactively tracking one or more sources and executing a callback function when the sources change.
How to Observe a ref Object
Assume we have a ref object; we can set up the observer as follows:
javascriptimport { ref, watch } from 'vue'; export default { setup() { const count = ref(0); watch(count, (newValue, oldValue) => { console.log(`count's value changes from ${oldValue} to ${newValue}`); }); return { count }; } }
In the above example, count is a reactive reference created using ref. Using the watch function to monitor changes in count, whenever the value of count changes, the provided callback function is triggered and prints the new and old values.
How to Observe a reactive Object
For reactive objects, the observation method is similar to ref, but we typically observe a specific property of the reactive object:
javascriptimport { reactive, watch } from 'vue'; export default { setup() { const state = reactive({ count: 0 }); watch(() => state.count, (newValue, oldValue) => { console.log(`count's value changes from ${oldValue} to ${newValue}`); }); return { state }; } }
In this example, state is a reactive object created using reactive. Here, we use a variant of watch that accepts a function as the first parameter, which returns the reactive property we want to observe (state.count). Whenever the count value changes, the callback function is triggered.
A More Complex Example
If we want to observe both ref and reactive objects simultaneously, we can combine them in a single watch:
javascriptimport { ref, reactive, watch } from 'vue'; export default { setup() { const count = ref(0); const state = reactive({ text: 'hello' }); watch([count, () => state.text], ([newCount, newText], [oldCount, oldText]) => { console.log(`count's value changes from ${oldCount} to ${newCount}`); console.log(`text's value changes from ${oldText} to ${newText}`); }); return { count, state }; } }
In this example, we observe both count and state.text simultaneously. By placing them in an array and using them in the watch function, we can handle their changes in a single callback, which is very useful when observing multiple sources and handling changes centrally.
Summary
Using Vue 3's watch API to set up observers for ref and reactive objects is straightforward and flexible, enabling us to execute specific logic when data changes, which is very helpful for building responsive user interfaces.