So, I am working on a big VueJS application, and I somehow I made a big mistake. I put a watch on a getter, and called an action in the watch which manipulated the state and reactively called the getter. Hence I was trapped in an infinite loop. For sometime my application was fine, but in some other component I again put a watch on that getter, and put a log there and then I saw my chrome console brimming with console messages. Then I fixed my watcher.
I am looking for a way to find if there are any other infinite watch loops in my Vue application. Since I cannot go and put a log in every other watchers. There are many.
You can put a log into every watcher programatically using a global mixin. This can be achieved using the following code:
Vue.mixin({
beforeCreate() {
if (this.$options.watch) {
Object.entries(this.$options.watch).forEach(([watcherKey, func]) => {
this.$options.watch[watcherKey] = new Proxy(func, {
apply(target, thisArg) {
console.log(`Called watcher ${target.name} on component ${thisArg.$options.name}`);
},
});
});
}
},
});
This code hooks into the global Vue instance and for every component, before the component is created, it enumerates through any watcher functions and wraps it in a proxy. The proxy implements the apply
trap to log to the console any time the watcher is called.
If this is too nuanced, you can look into using generic performance tools like Vue Performance Devtool or the Performance tab in Chrome Dev Tools: