https://stackoverflow.com/a/63800832/1497720
Typical watch syntax is watch(<variable>, <function to handle>)
but in this answer: https://stackoverflow.com/a/63800832/1497720
we have
watch(() => route.name, () => {
console.debug(`MyCoolComponent - watch route.name changed to ${route.name}`);
// Do something here...
// Optionally you can set immediate: true config for the watcher to run on init
//}, { immediate: true });
});
Can someone explain what's the syntax means?
CodePudding user response:
The full syntax of a watch helper is :
watch(param1,param2,param3)
param1 could be a ref
data or a getter function that returns another reactive data (prop, computed or reactive ...)
param2 is the callback handler that takes two parameters the new value and the old one
param3 is the watch options like {immediate:true,deep:true}
which is optional
CodePudding user response:
That's just another way of using vm.$watch API, please refer to the Vue documentation
The key point to take away here is that you can not only watch a data or a computed property, but also an expression. The expression only accepts dot-delimited paths. For more complex expressions, use a function instead.
This is an example:
vm.$watch(
function () {
// every time the expression `this.a this.b` yields a different result,
// the handler will be called. It's as if we were watching a computed
// property without defining the computed property itself
return this.a this.b
},
function (newVal, oldVal) {
// do something
}
)
So in your example above, it can simplify to this piece of code below:
watch('route.name', () => {
console.debug(`MyCoolComponent - watch route.name changed to ${route.name}`);
// Do something here...
// Optionally you can set immediate: true config for the watcher to run on init
//}, { immediate: true });
})