2
votes

In the Vue docs it is mentioned that computed properties are smartly cached as opposed to using regular methods:

In comparison, a method invocation will always run the function whenever a re-render happens. Why do we need caching? Imagine we have an expensive computed property...

My question is: Do watched properties also having caching like computed properties? (including Vuex watching, eg. using vm.$store.watch...)

2

2 Answers

2
votes

Behaviour of watchers will be same as behaviour of computed as computed is internally implemented using watchers. When one defines a computed property, vue internally sets watcher on the variables used in computed property, see the code below from source:

function makeComputedGetter (getter: Function, owner: Component): Function {
  const watcher = new Watcher(owner, getter, noop, {
    lazy: true
  })
  return function computedGetter () {
    if (watcher.dirty) {
      watcher.evaluate()
    }
    if (Dep.target) {
      watcher.depend()
    }
    return watcher.value
  }
}

So code written in computed or watch blocks will be executed only once, when the reactive data changes.

3
votes

While saurabh's answer is not wrong, I feel that it does not really answer the question.

The answer would be: no, watchers are not "cached" - that makes no sense, because watchers are functions that have side effects, but don't have return values and can't be used as properties.

So it is not necessary or sensible to cache anything for watchers.

But yes, both are only executed when the watched data changes.