background

From time to time in your work life, you will encounter a situation where the wrong data is displayed on a page and your front end colleague needs to locate it.

In a SPA application built using Vue, the final data displayed on the page, from initialization to final presentation, can be very simple or very complex. Encounter complex data flow, there is no appropriate method, troubleshooting will be very headache.

If you can see the call stack when the data changes, you can know what happened before the wrong data was generated, and what step of error caused the final error. By following the clues given by the call stack, you can quickly locate the problem.

example

<template>
  <div>
    <! -- Expected output: hello,world -->
    <! -- actual output: hello,woold -->
    {{ msg }}
    <button @click="f1">change msg</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: 'hello,',}},methods: {
    f1() {
      this.msg += 'w'
      this.f2();
    },
    f2() {
      this.msg += 'oo';
      this.f3();
    },
    f3() {
      this.msg += 'ld'}}};</script>
Copy the code

Myth – Interrupt the point in Watch to see the call stack

We can see the callbacks for F1 and MSG in the Call Stack on the right side of the page, but f2 and F3 are not visible. So f2 and F3 are missing, but in fact it’s F2 that causes the data error.

Why is the call information for F2 and F3 lost?

Since f1, F2, and F3 have all changed MSG to trigger the Watcher of MSG in the same microtask, since F1 is the first to trigger, f2 and F3 will not trigger. Finally, when Watcher calls back an operation, it only remembers that F1 triggered it, so the Call Stack can only see information about F1.

The right thing to do

Go to node_modules\vue\dist\vue.runtime.esm.js and add a breakpoint in the set method of defineReactive, where the key is the name of the variable to listen on.

Here, you can see itmsgComplete process of changes occurring, quickly locate to yesf2Causes problems.

conclusion

By looking at the call stack, you can quickly locate data errors without having to be familiar with the project. Instead of using console.log or spending a lot of time sorting out the logic of the code, the data flow is a lot less work.