current position:Home>Nexttick principle of vue3

Nexttick principle of vue3

2022-06-24 09:21:42yibucuo

1. Execute code

Case a

<script src="../../dist/vue.global.js"></script>
<div id="demo">
  <h1>
    <p>{
    {
    count}}</p>
  </h1>
</div>
<script>
  const {
     createApp, ref, toRefs, reactive, watch, onMounted, computed } = Vue
  var app = createApp({
    
    setup() {
    
      var count = ref(1)
      onMounted(() => {
    
        count.value++;
      })
      return {
     count }
    }
  })
  app.mount('#demo')
</script>

Case 2

<script src="../../dist/vue.global.js"></script>
<div id="demo">
  <h1>
    <p ref="ppp">{
    {
    count}}</p>
  </h1>
</div>
<script>
  const {
     createApp, ref, toRefs, reactive, watch, onMounted, computed } = Vue
  var app = createApp({
    
    setup() {
    
      var count = ref(1)
      var ppp = ref(null)
      onMounted(() => {
    
        count.value++;
        console.log(ppp.value.innerHTML);// 1
        Vue.nextTick(() => {
    
          console.log(ppp.value.innerHTML); // 2
        })
      })
      return {
     count, ppp }
    }
  })
  app.mount('#demo')
</script>

2. Breaking point

  1. Find files packages\runtime-core\src\scheduler.ts
  2. ctrl+f Input function flushJobs(, Put a breakpoint inside the function

3. The call stack diagrams of the two cases are as follows

 Insert picture description here

4. Case 2 code analysis

  1. In execution patch Recursive time , Will handle <p ref="ppp">{ {count}}</p> Medium ref="ppp", This is setRef
  2. Trigger setRef function
  3. Trigger queueEffectWithSuspense function
  4. Trigger queuePostFlushCb function
  5. Trigger queueCb function
  6. Trigger queueFlush function , Build a Promise Micro task execution flushJobs
  7. Trigger flushJobs function
function nextTick(
  this, fn
){
    
  const p = currentFlushPromise || resolvedPromise
  return fn ? p.then(this ? fn.bind(this) : fn) : p
}
const resolvedPromise = Promise.resolve()
let currentFlushPromise = null
function queueFlush() {
    
  if (!isFlushing && !isFlushPending) {
    
    isFlushPending = true
    currentFlushPromise = resolvedPromise.then(flushJobs)
  }
}

copyright notice
author[yibucuo],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240801439372.html

Random recommended