• vue组件的更新:异步、批量


    vue组件的更新:异步、批量

    Vue组件的更新:

    • 异步
    • 批量

    主要利用浏览器事件轮询的微任务机制来实现组件的异步批量更新。

    当侦测到数据变化,vue会开启一个队列,将相关联的Watcher实例存入队列,将回调函数存入callbacks队列。异步执行回调函数,遍历watcher队列进行渲染。

    • 异步: Vue更新DOM时是异步执行的。
      • 一旦侦测到数据变化,key对应的Dep实例就会通知更新:dep.notify()。notify(): 遍历subs中所有的watcher,调用update()方法
      • watcher.update():update方法会调用queueWatcher(this)将wathcer进行入队操作
        • queueWatcher(watcher):通过watcher.id, 来判断has数组中是否有,如果没有,将watcher推入queue队列中。如果已经push过了,就不在入队了。将该watcher入队的时候,还会调用nextTick(flushSchedulerQueue)方法。
        • nextTick(flushSchedulerQueue):nextTick():将watcher需要更新的回调函数push入callbacks数组,callbacks数组存放的是一系列需要执行的回调函数,callbacks:[()=>{cb.call(ctx)}]。
    • 批量:在同一个事件循环下,vue将更新放入微任务队列中,一次性更新该组件
      • 当同步代码执行完,浏览器会在更新页面之前,先清空微任务队列microtask queue,微任务队列中有一个callbacks,里面存放的是vue更新组件的一些列更新代码。同时微任务队列中还会存放一些vue组件中用户自定义的一些异步任务。
        • 如果同一个watcher被多次触发(每次该key对应的数据被重新赋值,就会触发一次该watcher.update()),只会被推入队列中一次。去重可避免不必要的计算和DOM操作。
        • 浏览器在下一个事件轮询前,清空微任务队列后,就会刷新一次页面。在同一个事件轮询的周期内,所有待更新watcher都会批量执行完,在下次刷新页面中一次性全部更新掉。
    • 异步策略:Vue内部对异步队列尝试使用Promise.reslove().then()、MutationObserver、setImmediate,如果执行环境不支持,则会采用 setTimeout(fn, 0) 代替。先尝试使用微任务方式,不行再用宏任务方式。

    异步批量更新流程图:
    data中的数据发生改变,key对应的dep就会触发notify(),notify方法:遍历相关的watcher,调用update方法。
    image

    批量异步更新源码

    当data中的某个数据更新时:

    ① 触发Object.defineProperty()中的setter访问器属性

    core/oberver/index.js:

    set: function reactiveSetter (newVal) {
          const value = getter ? getter.call(obj) : val
          /* eslint-disable no-self-compare */
          if (newVal === value || (newVal !== newVal && value !== value)) {
            return
          }
          /* eslint-enable no-self-compare */
          if (process.env.NODE_ENV !== 'production' && customSetter) {
            customSetter()
          }
          // #7981: for accessor properties without setter
          if (getter && !setter) return
          if (setter) {
            setter.call(obj, newVal)
          } else {
            val = newVal
          }
          childOb = !shallow && observe(newVal)
          dep.notify()
        }
    

    ② 调用dep.notify(): 遍历所有相关watcher,调用wathcer.update()

    core/oberver/dep.js:

    // 通知所有相关的watcher进行更新
      notify () {
        // stabilize the subscriber list first
        // 重新定义一个数组 subs ,该数组不会影响this.subs里面的元素。
        // slice(start,end): 选中从start开始,end(不包含)结束的元素,再返回一个新数组
        // this.subs.slice() = this.subs.slice(0) = this.subs.slice(0, this.subs.length)
        // this.subs中存放的是一个个的watcher实例
        const subs = this.subs.slice()
        if (process.env.NODE_ENV !== 'production' && !config.async) {
          // subs aren't sorted in scheduler if not running async
          // we need to sort them now to make sure they fire in correct
          // order
          subs.sort((a, b) => a.id - b.id)
        }
        for (let i = 0, l = subs.length; i < l; i++) {
          subs[i].update()
        }
      }
    

    ③ 执行watcher.update(): 判断是立即更新还是异步更新。若为异步更新,调用queueWatcher(this),将watcher入队,放到后面一起更新。

    core/oberver/watcher.js:

    update () {
        /* istanbul ignore else */
        if (this.lazy) {
          this.dirty = true
        } else if (this.sync) {
          //立即执行渲染
          this.run()
        } else {
          // watcher入队操作,后面一起执行渲染
          queueWatcher(this)
        }
    }
    

    ④ 执行queueWatcher(this): watcher进行去重等操作,push到queue队列中,再调用nextTick(flushSchedulerQueue)执行异步队列,传入回调函数 flushSchedulerQueue。

    core/oberver/scheduler.js:

    function queueWatcher (watcher: Watcher) {
      // has 标识,是一个数组,判断该watcher是否已在,避免在一个队列中添加相同的 Watcher
      const id = watcher.id
      if (has[id] == null) {
        has[id] = true
        // flushing 标识,处理 Watcher 渲染时,可能产生的新 Watcher。
        if (!flushing) {
          // 将当前 Watcher 添加到异步队列
          queue.push(watcher)
        } else {
          // 产生新的watcher就添加到排序的位置
          let i = queue.length - 1
          while (i > index && queue[i].id > watcher.id) {
            i--
          }
          queue.splice(i + 1, 0, watcher)
        }
        // queue the flush
        // waiting 标识,让所有的 Watcher 都在一个 tick 内进行更新。
        if (!waiting) {
          waiting = true
      
          if (process.env.NODE_ENV !== 'production' && !config.async) {
            flushSchedulerQueue()
            return
          }
          // 执行异步队列,并传入回调
          nextTick(flushSchedulerQueue)
        }
      }
    }
    

    ⑤ 执行nextTick(cb):将传入的flushSchedulerQueue函数处理后()=>{if(cb){cb.call(ctx)}...}传入callbacks数组中,调用timerFunc函数异步执行任务。

    core/util/next-tick.js:

    function nextTick (cb?: Function, ctx?: Object) {
      let _resolve
      // 此处的callbacks就是队列(回调数组),将传入的 flushSchedulerQueue 方法处理后添加到回调数组
      // cb:有可能是是用户在组件内部调用$nextTick(cb)传入的cb
      callbacks.push(() => {
        if (cb) {
          try {
            cb.call(ctx)
          } catch (e) {
            handleError(e, ctx, 'nextTick')
          }
        } else if (_resolve) {
          _resolve(ctx)
        }
      })
      if (!pending) {
        pending = true
        // 启动异步执行任务,此方法会根据浏览器兼容性,选用不同的异步策略
        timerFunc()
      }
      // $flow-disable-line
      if (!cb && typeof Promise !== 'undefined') {
        return new Promise(resolve => {
          _resolve = resolve
        })
      }
    }
    

    ⑥ timerFunc():根据浏览器兼容性,选用不同的异步方式执行flushCallbacks。由于宏任务耗费的时间是大于微任务的,所以优先选择微任务的方式,都不行时再使用宏任务的方式。

    core/util/next-tick.js:

    let timerFunc
      
    // 支持Promise则使用Promise异步的方式执行flushCallbacks
    if (typeof Promise !== 'undefined' && isNative(Promise)) {
      const p = Promise.resolve()
      timerFunc = () => {
        p.then(flushCallbacks)
        if (isIOS) setTimeout(noop)
      }
      isUsingMicroTask = true
    } else if (!isIE && typeof MutationObserver !== 'undefined' && (
      isNative(MutationObserver) ||
      MutationObserver.toString() === '[object MutationObserverConstructor]'
    )) {
      let counter = 1
      const observer = new MutationObserver(flushCallbacks)
      const textNode = document.createTextNode(String(counter))
      observer.observe(textNode, {
        characterData: true
      })
      timerFunc = () => {
        counter = (counter + 1) % 2
        textNode.data = String(counter)
      }
      isUsingMicroTask = true
    } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
      timerFunc = () => {
        setImmediate(flushCallbacks)
      }
    } else {
      // 实在不行再使用setTimeout的异步方式
      timerFunc = () => {
        setTimeout(flushCallbacks, 0)
      }
    }
    

    ⑦ flushCallbacks: 异步执行callbacks队列中的所有回调函数

    core/util.next-tick.js

    // 循环callbacks队列,执行里面所有函数flushSchedulerQueue,并清空队列
    function flushCallbacks () {
      pending = false
      const copies = callbacks.slice(0)
      callbacks.length = 0
      for (let i = 0; i < copies.length; i++) {
        copies[i]()
      }
    }
    

    ⑧ flushSchedulerQueue(): 遍历watcher队列,执行watcher.run()函数

    watcher.run():真正的渲染。

    function flushSchedulerQueue() {
      currentFlushTimestamp = getNow();
      flushing = true;
      let watcher, id;
      
      // 排序,先渲染父节点,再渲染子节点
      // 这样可以避免不必要的子节点渲染,如:父节点中 v-if 为 false 的子节点,就不用渲染了
      queue.sort((a, b) => a.id - b.id);
      
      // do not cache length because more watchers might be pushed
      // as we run existing watchers
      // 遍历所有 Watcher 进行批量更新。
      for (index = 0; index < queue.length; index++) {
        watcher = queue[index];
        if (watcher.before) {
          watcher.before();
        }
        id = watcher.id;
        has[id] = null;
        // 真正的更新函数
        watcher.run();
        // in dev build, check and stop circular updates.
        if (process.env.NODE_ENV !== "production" && has[id] != null) {
          circular[id] = (circular[id] || 0) + 1;
          if (circular[id] > MAX_UPDATE_COUNT) {
            warn(
              "You may have an infinite update loop " +
                (watcher.user
                  ? `in watcher with expression "${watcher.expression}"`
                  : `in a component render function.`),
              watcher.vm
            );
            break;
          }
        }
      }
      
      // keep copies of post queues before resetting state
      const activatedQueue = activatedChildren.slice();
      const updatedQueue = queue.slice();
      
      resetSchedulerState();
      
      // call component updated and activated hooks
      callActivatedHooks(activatedQueue);
      callUpdatedHooks(updatedQueue);
      
      // devtool hook
      /* istanbul ignore if */
      if (devtools && config.devtools) {
        devtools.emit("flush");
      }
    }
    

    ⑨ watcher.run(): watcher真正的更新函数是run,而非update

    core/observer/watcher.js:

      run () {
        if (this.active) {
          const value = this.get()
          if (
            value !== this.value ||
            // Deep watchers and watchers on Object/Arrays should fire even
            // when the value is the same, because the value may
            // have mutated.
            isObject(value) ||
            this.deep
          ) {
            // set new value
            const oldValue = this.value
            this.value = value
            // 用户自定义的watcher(在组件内使用watcher监听属性的变化)
            if (this.user) {
              const info = `callback for watcher "${this.expression}"`
              invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
            } else {
              // vue组件本身的更新
              // this.cb: 是new Vue()在$mount()挂载时创建new Watcher()传入的回调函数: updateComponent
              this.cb.call(this.vm, value, oldValue)
            }
          }
        }
      }
    

    ⑩ updateComponent(): watcher.run() 经过一系列的执行,最终执行的this.cb.call(this.vm, value, oldValue)这里的this.cb就是new Watcher传入的回调函数updateComponent, updateComponent中执行render(),让组件重新渲染, 再执行_update(vnode) ,再执行 patch()更新界面。

    ⑪ _update():根据是否有vnode分别执行不同的patch。

    Vue.nextTick(callback)

    Vue.nextTick(callback):在callback回调中,vue组件是异步更新完成后的状态。这里可以获取更新后的DOM元素

    Vue在更新DOM时是异步执行的,所以在修改data之后,并不能立刻获取到修改后的Dom元素。如果想在同步修改代码后,获取修改后的DOM元素,可以再Vue.nextTick(callback)中获取。

    为什么Vue.$nextTick 能获取更新后的DOM

    因为Vue.$nextTick 就是调用的nextTick 方法,在异步队列中执行回调函数

    Vue.prototype.$nextTick = function (fn: Function) {
      return nextTick(fn, this);
    };
    

    Vue组件异步更新demo

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>vue的批量、异步更新</title>
      <script src="../../dist/vue.js"></script>
    </head>
    <body>
    <div id="demo">
      <h3>vue的批量、异步更新</h3>
      <p id="p1">{{foo}}</p>
    </div>
    <script>
      new Vue({
        el: '#demo',
        data: {
          foo: 'ready~~'
        },
        beforeCreate() {
          console.log('★★★beforeCreate,还没有进行数据响应式,也没有wathcer实例。已经进行了$parent/$root/$children、事件初始化、$slots $nextTicket $createElement render。')
        },
        created() {
          console.log('★★★created,已经完成inject、state、provide初始化。响应式数据已经完成。没有wathcer实例。')
        },
        mounted() {
          console.log('★★★我已经进入mounted钩子函数,已经生成了Watcher实例了')
          
          // vue组件更新,是利用浏览器的事件轮询的微任务来操作的。★★★ 异步、批量
          // 1. 异步: 同步代码中进行数据重新赋值,view视图层中的代码是不会立即更新的。数据重新赋值,就会触发watcher的update方法,该方法会调用queueWatcher(this)方法,该方法调用nextTick(flushSchedulerQueue),nextTick():方法就是push入callbacks数组的方法,将需要更新的watcher实例push进微任务队列的一个callbacks数组中,callbacks数组存放的是一系列需要执行的回调函数,callbacks:[()=>{cb.call(ctx)}]。当然,如果watcher实例已经push进去了,下次更新,如果push的是同一个wathcer实例,是不会进这个callbacks数组的。同时,这个同步代码是不会立即改变view层的代码的,即这个组件是不会立即更新的。如果没有别的额外操作,是要等浏览器的6ms一次的刷新,清空浏览的microtask queue后,才会一起在view层中展现。
          // 2. 批量:同步改变响应式对象的值,wathcer的update函数,会将wathcer实例进行入队操作queueWatcher(this),一直等到所有同步代码执行完,并且清空微任务队列之后,才会批量的将所有变动都展示在页面上。
          this.foo = Math.random()
          // foo进行重新赋值,defineReactive方法中,使用Object.defineProperty()的访问器属性的setter来设置值,同时通知改key对应的Dep实例调用notify()方法
          // notify方法: 1.Dep对象的subs数组中存放的是与之关联的Watcher实例:① vue组件初始化生成的Watcher实例, ② 用户自定义的watcher监听的Watcher实例。 2. 遍历subs中watcher,依次调用watcher.update()方法
          // watcher的update()方法: 将该wathcer实例,进行入队操作: queueWatcher(this),该方法调用nextTick(flushSchedulerQueue),将该key的Dep实例关联的Watcher实例推入到callbacks数组中,等待浏览器清空微任务队列。此时callbacks中push进一个cb
          console.log('1:' + this.foo);
          this.foo = Math.random()
          // this.foo第二次同步代码赋值,watcher实例不会推入callbacks数组。即,进入queueWatcher(this)后,不会执行nextTick(flushSchedulerQueue)方法。此时callbacks中还是只有一个cb。nextTick():方法就是push入callbacks数组的方法
          console.log('2:' + this.foo);
          this.foo = Math.random()
          // this.foo第三次同步代码赋值,watcher实例不会推入callbacks数组。即,进入queueWatcher(this)后,不会执行nextTick(flushSchedulerQueue)方法。此时callbacks中还是只有一个cb。
          console.log('3:' + this.foo);
    
          // 此时同步代码还没执行完,至少,还没进入清空microtask queue,所以,view层的数据仍然是上一次的数据,即初始化的值。
          console.log('p1.innerHTML:' + p1.innerHTML)
    
          // Promise.resolve().then(() => {
          //     // 这里才是最新的值
          //     console.log('p1.innerHTML:' + p1.innerHTML)
          // })
    
          this.$nextTick(() => {
            // 这里才是最新的值
            // 使用this.$nextTick(cb),将()=>{cb.call(ctx)}push进callbacks,所以callbacks中,目前有2个[()=>{ flushSchedulerQueue.call(ctx)}, ()=>{ 此处的回调函数}]
            // 第一个cb是将view视图层的数据更新
            // 第二个cb是这里的console打印dom的innerHTML
            console.log('p1.innerHTML:' + p1.innerHTML)
          })
        }
      })
    
    </script>
    </body>
    </html>
    
    
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>vue的批量、异步更新</title>
      <script src="../../dist/vue.js"></script>
    </head>
    <body>
    <div id="demo">
      <h3>vue的批量、异步更新</h3>
      <p id="p1">{{foo}}</p>
    </div>
    <script>
      new Vue({
        el: '#demo',
        data: {
          foo: 'ready~~'
        },
        beforeCreate() {
          console.log('★★★beforeCreate,还没有进行数据响应式,也没有wathcer实例。已经进行了$parent/$root/$children、事件初始化、$slots $nextTicket $createElement render。')
        },
        created() {
          console.log('★★★created,已经完成inject、state、provide初始化。响应式数据已经完成。没有wathcer实例。')
        },
        mounted() {
          console.log('★★★我已经进入mounted钩子函数,已经生成了Watcher实例了')
          
          // vue组件更新,是利用浏览器的事件轮询的微任务来操作的。★★★ 异步、批量
          // 1. 异步: 同步代码中进行数据重新赋值,view视图层中的代码是不会立即更新的。数据重新赋值,就会触发watcher的update方法,该方法会调用queueWatcher(this)方法,该方法调用nextTick(flushSchedulerQueue),nextTick():方法就是push入callbacks数组的方法,将需要更新的watcher实例push进微任务队列的一个callbacks数组中,callbacks数组存放的是一系列需要执行的回调函数,callbacks:[()=>{cb.call(ctx)}]。当然,如果watcher实例已经push进去了,下次更新,如果push的是同一个wathcer实例,是不会进这个callbacks数组的。同时,这个同步代码是不会立即改变view层的代码的,即这个组件是不会立即更新的。如果没有别的额外操作,是要等浏览器的6ms一次的刷新,清空浏览的microtask queue后,才会一起在view层中展现。
          // 2. 批量:同步改变响应式对象的值,wathcer的update函数,会将wathcer实例进行入队操作queueWatcher(this),一直等到所有同步代码执行完,并且清空微任务队列之后,才会批量的将所有变动都展示在页面上。
    
          // callbacks = []
          // microtaskQueue = [callbacks]
          this.$nextTick(() => {
            // 这里才是最新的值
            // 使用this.$nextTick(cb),将()=>{cb.call(ctx)}push进callbacks,所以callbacks中,目前有2个[()=>{ flushSchedulerQueue.call(ctx)}, ()=>{ 此处的回调函数}]
            // 第一个cb是将view视图层的数据更新
            // 第二个cb是这里的console打印dom的innerHTML
            console.log('$nextTick: p1.innerHTML:' + p1.innerHTML)
          })
          // callbacks: [()=>{$nextTickCB()}]
          // microtaskQueue = [callbacks]
    
          this.foo = Math.random()
          console.log('4:' + this.foo);
          // callbacks: [()=>{$nextTickCB()}, flushSchedulerQueue]
          // microtaskQueue = [callbacks]
          this.foo = Math.random()
          console.log('5:' + this.foo);
    
          console.log('p1.innerHTML:' + p1.innerHTML)
    
          // 4, 5, p1.innerHTML:reader~~,  $nextTick: p1.innerHTML:reader~~
    
        }
      })
    
    
    </script>
    </body>
    </html>
    
    
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>vue的批量、异步更新</title>
      <script src="../../dist/vue.js"></script>
    </head>
    <body>
    <div id="demo">
      <h3>vue的批量、异步更新</h3>
      <p id="p1">{{foo}}</p>
    </div>
    <script>
      new Vue({
        el: '#demo',
        data: {
          foo: 'ready~~'
        },
        beforeCreate() {
          console.log('★★★beforeCreate,还没有进行数据响应式,也没有wathcer实例。已经进行了$parent/$root/$children、事件初始化、$slots $nextTicket $createElement render。')
        },
        created() {
          console.log('★★★created,已经完成inject、state、provide初始化。响应式数据已经完成。没有wathcer实例。')
        },
        mounted() {
          console.log('★★★我已经进入mounted钩子函数,已经生成了Watcher实例了')
    
          // vue组件更新,是利用浏览器的事件轮询的微任务来操作的。★★★ 异步、批量
          // 1. 异步: 同步代码中进行数据重新赋值,view视图层中的代码是不会立即更新的。数据重新赋值,就会触发watcher的update方法,该方法会调用queueWatcher(this)方法,该方法调用nextTick(flushSchedulerQueue),nextTick():方法就是push入callbacks数组的方法,将需要更新的watcher实例push进微任务队列的一个callbacks数组中,callbacks数组存放的是一系列需要执行的回调函数,callbacks:[()=>{cb.call(ctx)}]。当然,如果watcher实例已经push进去了,下次更新,如果push的是同一个wathcer实例,是不会进这个callbacks数组的。同时,这个同步代码是不会立即改变view层的代码的,即这个组件是不会立即更新的。如果没有别的额外操作,是要等浏览器的6ms一次的刷新,清空浏览的microtask queue后,才会一起在view层中展现。
          // 2. 批量:同步改变响应式对象的值,wathcer的update函数,会将wathcer实例进行入队操作queueWatcher(this),一直等到所有同步代码执行完,并且清空微任务队列之后,才会批量的将所有变动都展示在页面上。
    
          // callbacks:[]
          // microtaskQueue : []
          Promise.resolve().then(()=>{
            console.log('Promise: p1.innerHTML:' + p1.innerHTML)
          })
          // callbacks: []
          // microtaskQueue = [p.then()]
    
          this.foo = Math.random()
          console.log('8:' + this.foo);
          // callbacks: [flushSchedulerQueue]
          // microtaskQueue = [p.then(),callbacks]
          this.foo = Math.random()
          console.log('9:' + this.foo);
          console.log('p1.innerHTML:' + p1.innerHTML)
    
          // 8, 9, p1.innerHTML:ready~~, Promise: p1.innerHTML:ready~~
    
        }
      })
    
    </script>
    </body>
    </html>
    
    
    <template>
      <p id="test">{{foo}}</p>
    </template>
    <script>
      
    export default{
      data(){
        return {
          foo: 'foo'
        }
      },
      mounted() {
        // callbacks:[]
        // cb: ()=>{console.log('nextTick:test.innerHTML:' + test.innerHTML);}
        let test  = document.querySelector('#test');
        
    // callbacks:[cb]
        this.$nextTick(() => {
          // nextTick回调是在触发更新之前就放入callbacks队列,
          // 压根没有触发watcher.update以及以后的一系列操作,所以也就没有执行到最后的watcher.run()实行渲染
          // 所以此处DOM并未更新
          console.log('nextTick:test.innerHTML:' + test.innerHTML);
        })
        
    // callbacks: [cb, flushSchedulerQueue]
        this.foo = 'foo1';
        // vue在更新DOM时是异步进行的,所以此处DOM并未更新
        console.log('1.test.innerHTML:' + test.innerHTML); 
        
    // callbacks: [cb, flushSchedulerQueue]
        this.foo = 'foo2';
        // 此处DOM并未更新,且先于异步回调函数前执行
        console.log('2.test.innerHTML:' + test.innerHTML); 
      }
    }
    </script>
    cb: ()=>{console.log('nextTick:test.innerHTML:' + test.innerHTML);}
    callbacks:[]
    callbacks:[cb]
    callbacks: [cb, flushSchedulerQueue]
    callbacks: [cb, flushSchedulerQueue]
    执行结果:
    1.test.innerHTML:foo
    2.test.innerHTML:foo
    nextTick:test.innerHTML:foo
    
    <template>
      <p id="test">{{foo}}</p>
    </template>
    <script>
      
    export default{
      data(){
        return {
          foo: 'foo'
        }
      },
      mounted() {
        
    // callbacks: []
    // microtaskQueue: []
    // macrotaskQueue: []
        
        
        let test  = document.querySelector('#test');
        this.$nextTick(() => {
          // nextTick回调是在触发更新之前就放入callbacks队列,
          // 压根没有触发watcher.update以及以后的一系列操作,所以也就没有执行到最后的watcher.run()实行渲染
          // 所以此处DOM并未更新
          console.log('nextTick:test.innerHTML:' + test.innerHTML); 
        })
      
    // callbacks: [cb]    
    // microtaskQueue: [callbacks]
    // macrotaskQueue: []
        
        
        this.foo = 'foo1';
        
    // callbacks: [cb, flushSchedulerQueue]    
    // microtaskQueue: [callbacks]
    // macrotaskQueue: []    
        
        // vue在更新DOM时是异步进行的,所以此处DOM并未更新
        console.log('1.test.innerHTML:' + test.innerHTML); 
        this.foo = 'foo2';
        
    // callbacks: [cb, flushSchedulerQueue]    
    // microtaskQueue: [callbacks]
    // macrotaskQueue: []   
        
        
        // 此处DOM并未更新,且先于异步回调函数前执行
        console.log('2.test.innerHTML:' + test.innerHTML); 
      
        Promise.resolve().then(() => {
          console.log('Promise:test.innerHTML:' + test.innerHTML); 
        });
        
    // callbacks: [cb, flushSchedulerQueue]    
    // microtaskQueue: [callbacks, Promise.resolve().then]
    // macrotaskQueue: []  
        
        setTimeout(() => {
            console.log('setTimeout:test.innerHTML:' + test.innerHTML);
        });
        
    // callbacks: [cb, flushSchedulerQueue]    
    // microtaskQueue: [callbacks, Promise.resolve().then]
    // macrotaskQueue: [setTimeout]      
        
      }
    }
    </script>
    执行结果:
    1.test.innerHTML:foo
    2.test.innerHTML:foo
    nextTick:test.innerHTML:foo
    Promise:test.innerHTML:foo2
    setTimeout:test.innerHTML:foo2
    
    <template>
      <p id="test">{{foo}}</p>
    </template>
    <script>
      
    export default{
      data(){
        return {
          foo: 'foo'
        }
      },
      mounted() {
        
        
    // callbacks: []
    // microtaskQueue: []
    // macrotaskQueue: []    
        
        let test  = document.querySelector('#test');
        // Promise 和 setTimeout 依旧是等到DOM更新后再执行
        
        Promise.resolve().then(() => {
          console.log('Promise:test.innerHTML:' + test.innerHTML); 
        });
        
    // callbacks: []
    // microtaskQueue: [Promise.resolve().then]
    // macrotaskQueue: []
        
        setTimeout(() => {
            console.log('setTimeout:test.innerHTML:' + test.innerHTML);
        });
            
    // callbacks: []
    // microtaskQueue: [Promise.resolve().then]
    // macrotaskQueue: [setTimeout]
        
        
        this.$nextTick(() => {
          // nextTick回调是在触发更新之前就放入callbacks队列,
          // 压根没有触发watcher.update以及以后的一系列操作,所以也就没有执行到最后的watcher.run()实行渲染
          // 所以此处DOM并未更新
          console.log('nextTick:test.innerHTML:' + test.innerHTML); 
        })
               
    // callbacks: [cb]
    // microtaskQueue: [Promise.resolve().then, callbacks]
    // macrotaskQueue: [setTimeout]
        
           
        this.foo = 'foo1';
                   
    // callbacks: [cb, flushSchedulerQueue]
    // microtaskQueue: [Promise.resolve().then, callbacks]
    // macrotaskQueue: [setTimeout]
        
    
        // vue在更新DOM时是异步进行的,所以此处DOM并未更新
        console.log('1.test.innerHTML:' + test.innerHTML); 
        this.foo = 'foo2';
                       
    // callbacks: [cb, flushSchedulerQueue]
    // microtaskQueue: [Promise.resolve().then, callbacks]
    // macrotaskQueue: [setTimeout]
        
        // 此处DOM并未更新,且先于异步回调函数前执行
        console.log('2.test.innerHTML:' + test.innerHTML); 
      }
    }
    </script>
    执行结果:
    1.test.innerHTML:foo
    2.test.innerHTML:foo
    Promise:test.innerHTML:foo
    nextTick:test.innerHTML:foo2
    setTimeout:test.innerHTML:foo2
    

    只有在microtaskQueue队列中执行到callbacks队列时,页面的dom元素的值才会改变。

    在microtaskQueue队列执行到callbacks队列之前所以的代码获取的dom元素都是旧值

  • 相关阅读:
    NET在后置代码中输入JS提示语句(背景不会变白)
    陈广老师C#参考视频 方法的参数传递 总结
    preventDefault和stopPropagation两个方法的区别
    zerobased budgeting: 零基预算法
    JS: 关于自执行的匿名函数(整理)
    通过实例理解javascript 的call()与apply()
    setTimeout注意几点
    js constructor
    canphp的数据库操作
    JS事件监听器
  • 原文地址:https://www.cnblogs.com/shine-lovely/p/14945547.html
Copyright © 2020-2023  润新知