In Vue.js, the watchEffect function is used to monitor changes in reactive data and execute side effects. When the reactive state being observed by watchEffect changes, watchEffect will re-execute.
Main Uses
-
Automatic Dependency Detection: Unlike
watch,watchEffectdoes not require explicitly specifying the data source to observe; it automatically collects dependencies. This means all reactive references used within the callback function ofwatchEffectwill be monitored. -
Simplified Side Effect Implementation:
watchEffectis ideal for scenarios where side effects need to be executed after data changes, such as automatic data saving and view updates.
Example
Suppose you have a Vue component containing a form and a user object. You want to automatically save this data when user data changes. Using watchEffect can succinctly implement this requirement:
vue<template> <div> <input v-model="user.name" placeholder="Enter your name"> <input v-model="user.age" placeholder="Enter your age"> </div> </template> <script> import { watchEffect, reactive } from 'vue'; export default { setup() { const user = reactive({ name: '', age: 0 }); watchEffect(() => { console.log('Detected change in user data:', user); // Assume saveUser is a function to save user data to the server saveUser(user); }); return { user }; } } </script>
In this example, watchEffect automatically monitors changes to the name and age properties of the user object. Once these data are updated, the code inside watchEffect executes, invoking the saveUser function to handle data saving.
In summary, watchEffect is a valuable feature that enables developers to automatically handle reactive data changes in a declarative manner.