SoFunction
Updated on 2025-04-05

How many page updates will be triggered in vue interview created? Detailed explanation of how many data modifications will trigger data updates in vue interview

Interview questions:

createdHow many page updates will be triggered if data is modified twice during the life cycle?

1. Synchronous

Let me give you a simple synchronization example:

new Vue({
  el: "#app",
  template: `<div>
    <div>{{count}}</div>
  </div>`,
  data() {
    return {
      count: 1,
    }
  },
  created() {
     = 2;
     = 3;
  },
});

existcreatedDuring the life cycle, = 2and = 3The way toReassign value.

The answer is thrown here directly: render once.

Why?

This is related to the responsive processing of data. Let’s first look at the logic of responsive processing:

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  // Focus: Create a publisher instance  const dep = new Dep()
  const property = (obj, key)
  if (property &amp;&amp;  === false) {
    return
  }
  // cater for pre-defined getter/setters
  const getter = property &amp;&amp; 
  const setter = property &amp;&amp; 
  if ((!getter || setter) &amp;&amp;  === 2) {
    val = obj[key]
  }
  let childOb = !shallow &amp;&amp; observe(val)
  (obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? (obj) : val
      if () {
        // Focus: Collect the rendering watcher currently being calculated        ()
        if (childOb) {
          ()
          if ((value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? (obj) : val
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal &amp;&amp; value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (.NODE_ENV !== 'production' &amp;&amp; customSetter) {
        customSetter()
      }
      // #7981: for accessor properties without setter
      if (getter &amp;&amp; !setter) return
      if (setter) {
        (obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow &amp;&amp; observe(newVal)
      // Point: When the data changes, the publisher instance dep will notify the collected watcher for updates      ()
    }
  })
}

During the data responsive processing phase, a publisher is instantiateddep, and passThe way to define the current datagetandsetfunction. Generating virtualvNodeThe stage will triggergetThe currently being calculated will be rendered in the functionWatcherThe collection, at this time, the publisherdepofsubsThere will be one more rendering in itWatcherExample. When the data changes, it will triggersetFunction, notify publisherdepmiddlesubsIn-housewatcherMake updates.

As for how many updates will be triggered by the data modification, it will be with the current publisher.depofsubsSeveral renderings were collectedwatcherIt's relevant, please read it againwatcherCollect andcreatedThe order between executions:

._init = function (options) {
    // ...
    initState(vm);
    // ...
    callHook(vm, 'created');
    // ...
    if (vm.$) {
      vm.$mount(vm.$);
    }
}

We knowinitState(vm)The data is responsively processed, but the publisher is nowdepofsubsOr an empty array. When executedcallHook(vm, 'created')When it is executed = 2and = 3The logic ofsetin the functionNotification collectedwatcherMake updates. However, at this timedepofsubsIt's an empty array, which is equivalent to doing nothing.

Only invm.$mount(vm.$)During execution, generate virtualvNodeIt will only be rendered whenWatcherCollect, at this time,depofsubsNot empty. Finally, byvm.$mount(vm.$)A rendering of the page was performed, but it was not because=2or=3And triggers unnecessary page updates.

In short, it iscreatedThe execution of logic within the hook function is renderedwatcherThe collection was performed before, so the page update caused by data changes was not caused.

2. Asynchronous

After talking about the synchronization scenario, let’s give another asynchronous example:

new Vue({
  el: "#app",
  template: `<div>
    <div>{{count}}</div>
  </div>`,
  data() {
    return {
      count: 1,
    }
  },
  created() {
    setTimeout(() => {
       = 2;
    }, 0)
    setTimeout(() => {
       = 3;
    }, 0)
  },
});

existcreatedDuring the life cycle, it is executed asynchronously = 2and = 3The way toReassign value.

The answer is thrown here directly: render once for the first time, and the page is updated twice due to data changes.

Why?

This is witheventLoopThe event loop mechanism is related, we knowjavascriptis a single threaded language when we passnew VueDuring instantiation, the initialization method will be executedthis._initMethod, startVueThe underlying processing logic. When encounteringsetTimeoutDuring asynchronous operation, it will be pushed into the asynchronous queue and wait for the current synchronization task to be executed before the asynchronous queue is removed and the first element of the queue will be executed.

In the current example,initState(vm)The data is processed responsively in stages. When executedcallHook(vm, 'created')When it is = 2and = 3The logic is pushed into the asynchronous queue and waits for execution. Continue to executevm.$mount(vm.$)During the process, virtual will be generatedvNode, and then triggergetRendering of functionsWatcherCollect, at this time,depofsubsThere is a rendering in itwatcher

After the first page rendering is completed, it will be executed=2The logic of data modification will triggersetin the function, the publisher at this timedepofsubsNot empty will cause the page to be updated. Similarly,=3It will cause the page data to be updated again. That is to say, the first rendering is because=2and=3It will also cause the page to be updated twice.

III. Additional

If I change the value anddataWhat about the values ​​defined in the same?

new Vue({
  el: "#app",
  template: `<div>
    <div>{{count}}</div>
  </div>`,
  data() {
    return {
      count: 1,
    }
  },
  created() {
    setTimeout(() => {
       = 1;
    }, 0)
  },
});

At this time, it is triggeringsetIn the logic ofif (newVal === value || (newVal !== newVal && value !== value)) { return }The logic will not be executed again, the data of the data in this scenario will not cause the page to be updated again.

Summarize

From the life cyclecreatedand the order of page rendering,triggergetandsetThe mechanism of the function, andeventLoopStart with the event loop mechanism and analyze itcreatedThe problem of how many page updates will be triggered by the two data modifications will be much clearer.

The above is the detailed explanation of the two data modifications in the vue interview created that will trigger several page updates. For more information about the update of the vue created data modification page, please pay attention to my other related articles!