watch
Functions are functions used in Vue to monitor responsive data changes and execute corresponding logic or side effects when the data changes. It can monitor changes in responsive data, including object properties, changes in arrays, nested objects and arrays, etc.
watch
There are two ways to use functions: callback-based watch and listener-based watch.
-
Watch based on callback function:
import { watch } from 'vue'; const count = ref(0); watch(count, (newValue, oldValue) => { console.log(`count的值从${oldValue}变为${newValue}`); });
In the example above, changes
watch
are monitored by the functioncount
. Whenevercount
the value of is changed, the callback function will be triggered, passing in the current valuenewValue
and the last valueoldValue
. In the callback function, corresponding logic or side effects can be performed. -
Listener based watch:
import { watch } from 'vue'; const obj = reactive({ name: 'Tom', age: 18, }); watch(() => obj.age, (newValue, oldValue) => { console.log(`age的值从${oldValue}变为${newValue}`); });
In the example above, changes
watch
are monitored by the functionobj.age
. The listener here is a reactive getter function, andobj.age
the callback function will only be triggered when the value of the value changes.
In addition to the method based on the callback function and the listener, watch
the function also provides some other options to control the monitoring behavior, such as immediate
the option to execute the callback function once immediately.
In summary, watch
functions can be used to monitor changes in reactive data and execute corresponding logic or side effects when the data changes.