Watchers
Vue watchers programmatically observe component data and run whenever a particular property changes. Watched data can contain two arguments: oldVal
and newVal
. This can help you when writing expressions to compare data before writing or binding new values. Watchers can observe objects as well as string
, number
, and array
types. When observing objects, it will only trigger the handler if the whole object changes.
In Chapter 1, Starting Your First Vue Project, we introduced life cycle hooks that run at specific times during a component's lifespan. If the immediate
key is set to true
on a watcher, then when this component initializes it will run this watcher on creation. You can watch all keys inside of any given object by including the key and value deep: true
(default is false
) To clean up your watcher code, you can assign a handler argument to a defined Vue method, which is best practice for large projects.
Watchers complement the usage of computed data since they...