Tracing or Debugging Vue.js Reactivity: The computed tree

Michael Gallagher
Feb 26 · 8 min read

Why Reactive code might need tuning

This is the computed tree, and if it isn’t clear, then maybe flipping a seemingly innocent boolean could trigger a refresh of 100 components.

Nuts and Bolts

Ever seen __ob__ when debugging in browser developer tools?

By Example

How does computed reactivity work?

Hold up I hear you say, why would all 3 Watchers depend on the state property?

So what can __ob__ tell us about computed reactivity?

this.$store.state.users[2].__ob__.dep.subs[5]

Vuex Getters

const watchers = store._vm._computedWatchers;
Object.keys(watchers).forEach(key => {
  watchers[key].watcherName = key;
});

Dependency instances for Object Properties

My cheeky trick is to add a Watcher to the property and then grab the Dependency off the Watcher.

const tempVm = new Vue();
tempVm.$watch(() => store.state.users[2].name, () => {});
const tempWatch = tempVm._watchers[0];// now pull the subs from the deps
tempWatch.deps.forEach(dep => dep.subs
  .filter(s => s !== tempWatch)
  .forEach(s => subs.add(s)));

Want it wrapped up in a tool?

{
  "computed": [
    "currentUser",
    "validCurrentUser",
    "Comp.upperCaseName"
  ],
  "components": [
    "Comp"
  ],
  "unrecognised": 1
}
{
  "computed": [
    "validCurrentUser",
    "Comp.upperCaseName"
  ],
  "components": [
    "Comp"
  ],
  "unrecognised": 1
}

One last point…

DailyJS

JavaScript news and opinion.

Michael Gallagher

Written by

Living in the vibrant city of Buenos Aires, developing project management software with Teamwork. Modern JS is my passion, Vue my tool of choice

DailyJS

DailyJS

JavaScript news and opinion.