tomwang1013
tomwang1013

Reputation: 1425

In Vue.js, How to find what data changes cause a component to re-render?

In Vue.js, a component does re-render(update) when some data changes. Sometimes the re-render frequency is too often and i want to find out which data's change cause this re-render. How to find out the changed data causing the re-render?

Upvotes: 10

Views: 6767

Answers (3)

troy
troy

Reputation: 419

Vue 3 and Vue 2.7 supported this natively

export default {
  renderTracked(event) {
    debugger
  },
  renderTriggered(event) {
    debugger
  }
}

see https://vuejs.org/guide/extras/reactivity-in-depth.html#component-debugging-hooks

Upvotes: 0

LMK
LMK

Reputation: 1561

Further to above, and as noted in the comments the deep watcher will only work if the component's own data has changed. A more conclusive method is shown below (also posted to https://stackoverflow.com/a/69275418/960380)

Using the F12 dev tools in Chrome, you can track down what is triggering your component to re-render. Add an updated hook to your component as below:

updated() {

            if (!this.updateCnt)
                this.updateCnt = 1;
           
            if (this.updateCnt > 1) { // set to desired
                debugger;
            }
            console.log(`Updated ${this.updateCnt++} times`);
        }
    }

Refresh your page in Chrome with F12 tools open and wait for breakpoint to be hit. In the Sources tab, you will see the call stack on the right, with your updated() function as the current stack frame. Look back up the call stack and eventually you should see the code that caused the update to trigger. In my case, it was reactiveSetter() in the vue runtime, which was triggered by me setting a property in a parent component.

Upvotes: 1

FitzFish
FitzFish

Reputation: 8629

Using deep-diff and a simple watcher, you can easily find the difference between a previous copy of your vm data.

new Vue({
  el: "#app",
  data: {
    counter: 0
  },
  mounted() {
    let oldData = JSON.parse(JSON.stringify(this.$data));
    this.$watch(vm => vm.$data, (newData) => {
      console.log(DeepDiff.diff(oldData, newData));
      oldData = JSON.parse(JSON.stringify(newData));
    }, {
      deep: true
    });
  },
  methods: {
    add: function() {
      this.counter++;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>
<div id="app">
  <button @click="add"> +1 </button> {{ counter }}
</div>

Upvotes: 6

Related Questions