How vuejs knows the dependencies of computed properties for caching?

Hello commuty.
I read the guide, the api, and try to read the source code, and still not finding an answer.

Please see my question on StackOverflow:

1 Like

This is achieved by Object.defineProperty(). From a high-level perspective, with reference to your StackOverflow example:

  1. Computed property myComputed is called
  2. Inside myComputed, myValue is accessed
  3. Inside myValue's getter, Vue registers myValue as a dependency of myComputed
  4. Inside myValue's setter, Vue, knowing that myComputed depends on myValue, recalculates myComputed

The whole process is supported by a Dep dependency tracker.

For a way better and more in-depth explanation, I’d suggest reading skyronic’s solid article: Vue.js Internals: How computed properties work.

4 Likes

Please see my second example in the question.

If this is the mechanism. It will be buggy. In the second example. If I change the flag value to 1, I will get the caching answer when (flag==2), instead of new answer.

No, not buggy. You use it wrong. Our docs clearly state that computed properties re-caclulate if any reactive dependencies change.

In your example, flag is not reactive (because it’s not in the component’s data), therefore, no recalculation will happen.

1 Like

To add more clarification to @linusborg’s answer above – mentioned Dep dependency tracker, as its name says, tracks the dependencies throughout the Vue system and makes sure they’re in proper order. Any outside variables (flag in your case) can’t be tracked, and hence, can’t trigger reactivity.

Thanks you

The URL to the article is no longer valid. It should now be:

http://web.archive.org/web/20190523191010/http://skyronic.com:80/blog/vuejs-internals-computed-properties

This really ought to be hyperlinked from https://vuejs.org/v2/guide/computed.html because this really freaked me out.