How to watch ref and reactive object with a single watcher in Vue3
In Vue 3, and are two core APIs for creating reactive data. We can monitor changes in these reactive data using the function. 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 ObjectAssume we have a object; we can set up the observer as follows:In the above example, is a reactive reference created using . Using the function to monitor changes in , whenever the value of changes, the provided callback function is triggered and prints the new and old values.How to Observe a ObjectFor objects, the observation method is similar to , but we typically observe a specific property of the object:In this example, is a reactive object created using . Here, we use a variant of that accepts a function as the first parameter, which returns the reactive property we want to observe (). Whenever the value changes, the callback function is triggered.A More Complex ExampleIf we want to observe both and objects simultaneously, we can combine them in a single :In this example, we observe both and simultaneously. By placing them in an array and using them in the function, we can handle their changes in a single callback, which is very useful when observing multiple sources and handling changes centrally.SummaryUsing Vue 3's API to set up observers for and objects is straightforward and flexible, enabling us to execute specific logic when data changes, which is very helpful for building responsive user interfaces.