美文网首页
nextTick的问题

nextTick的问题

作者: 没了提心吊胆的稗子 | 来源:发表于2019-12-12 16:55 被阅读0次

    Vue官方文档中的说明:

    Vue异步执行DOM更新。只要观察到数据变化,Vue将开启一个任务队列,并缓冲在同一事件循环中发生的所有数据变化。如果同一个watcher被多次触发,只会被推入到队列中一次。这种在缓冲时去重重复数据对于避免不必要的计算和DOM操作上非常重要。然后,在下一个事件循环的Tick中,Vue刷新队列并执行实际(已经去重)的工作。

    也就是说在一个事件循环中发生的数据改变都会在下一个事件循环的Tick中(也有可能是当前的Tick微任务执行阶段)触发视图更新。到底是哪个阶段,则取决于nextTick函数使用的是Promise/MutationObserver还是setTimeout

    Vue部分源码

    this.deep = this.user = this.lazy = this.sync = false
    ...
      update () {
        if (this.lazy) {
          this.dirty = true
        } else if (this.sync) {
          //  同步执行run直接渲染视图
          this.run()
        } else {
          // 第一次执行(异步)推送到观察者队列中,下一个tick的时候调用
          queueWatcher(this)
        }
      }
    ...
    

    可以看出this.deep =this.user = this.lazy = this.sync初始值都被设置为false,所以第一次触发视图更新的时候会执行queueWatcher函数

    export function queueWatcher (watcher: Watcher) {
      const id = watcher.id
      // 查看当前watcher的id是否存在,已存在就跳过,不存在就标记哈希表,下次校验的时候使用
      if (has[id] == null) {
        has[id] = true
        if (!flushing) {
          //   没有flush掉就直接push到队列中
          queue.push(watcher)
        } else {
          // if already flushing, splice the watcher based on its id
          // if already past its id, it will be run next immediately.
          let i = queue.length - 1
          while (i > index && queue[i].id > watcher.id) {
            i--
          }
          queue.splice(i + 1, 0, watcher)
        }
        // queue the flush
        if (!waiting) {
          //  waiting变量 保证flushSchedulerQueue回调只会被置入callbacks中一次
          waiting = true
          nextTick(flushSchedulerQueue)
        }
      }
    }
    

    其中的flushSchedulerQueue函数就是把queue中的所有watcher取出来并执行相应的视图更新操作。

    function flushSchedulerQueue () {
      flushing = true
      let watcher, id
      ...
     for (index = 0; index < queue.length; index++) {
        watcher = queue[index]
        id = watcher.id
        has[id] = null
        watcher.run()
        ...
      }
    }
    

    nextTick

    export const nextTick = (function () {
      const callbacks = []
      let pending = false
      let timerFunc
    
      function nextTickHandler () {
        pending = false
        const copies = callbacks.slice(0)
        callbacks.length = 0
        for (let i = 0; i < copies.length; i++) {
          copies[i]()
        }
      }
    
      // An asynchronous deferring mechanism.
      // In pre 2.4, we used to use microtasks (Promise/MutationObserver)
      // but microtasks actually has too high a priority and fires in between
      // supposedly sequential events (e.g. #4521, #6690) or even between
      // bubbling of the same event (#6566). Technically setImmediate should be
      // the ideal choice, but it's not available everywhere; and the only polyfill
      // that consistently queues the callback after all DOM events triggered in the
      // same loop is by using MessageChannel.
      /* istanbul ignore if */
      if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
        timerFunc = () => {
          setImmediate(nextTickHandler)
        }
      } else if (typeof MessageChannel !== 'undefined' && (
        isNative(MessageChannel) ||
        // PhantomJS
        MessageChannel.toString() === '[object MessageChannelConstructor]'
      )) {
        const channel = new MessageChannel()
        const port = channel.port2
        channel.port1.onmessage = nextTickHandler
        timerFunc = () => {
          port.postMessage(1)
        }
      } else
      /* istanbul ignore next */
      if (typeof Promise !== 'undefined' && isNative(Promise)) {
        // use microtask in non-DOM environments, e.g. Weex
        const p = Promise.resolve()
        timerFunc = () => {
          p.then(nextTickHandler)
        }
      } else {
        // fallback to setTimeout
        timerFunc = () => {
          setTimeout(nextTickHandler, 0)
        }
      }
    
      return function queueNextTick (cb?: Function, ctx?: Object) {
        let _resolve
        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, reject) => {
            _resolve = resolve
          })
        }
      }
    })()
    

    nextTick主要做了两件事,一是生成timeFunc,把回调作为microTask或者macroTask参与到事件循环中;二是把回调放入一个callbacks队列,等待合适的时机通过nextTickHandler执行调用。

     if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
        timerFunc = () => {
          setImmediate(nextTickHandler)
        }
      } else if (typeof MessageChannel !== 'undefined' && (
        isNative(MessageChannel) ||
        // PhantomJS
        MessageChannel.toString() === '[object MessageChannelConstructor]'
      )) {
        const channel = new MessageChannel()
        const port = channel.port2
        channel.port1.onmessage = nextTickHandler
        timerFunc = () => {
          port.postMessage(1)
        }
      } else
      /* istanbul ignore next */
      if (typeof Promise !== 'undefined' && isNative(Promise)) {
        // use microtask in non-DOM environments, e.g. Weex
        const p = Promise.resolve()
        timerFunc = () => {
          p.then(nextTickHandler)
        }
      } else {
        // fallback to setTimeout
        timerFunc = () => {
          setTimeout(nextTickHandler, 0)
        }
      }
    

    timerFunc函数的优先定义顺序涉及到两个概念:marcoTask -> microTask。按照PromiseMutationObserversetTimeout的优先级去调用回调函数的,前两个会成成microTask,后者生成marcoTask
    浏览器在一个Tick执行完marcoTask后会清空当前Tick所有的microTask再进行UI渲染,所以这样设置优先级,把DOM更新的操作放在microTask执行的阶段来完成。
    值得注意的是:marcoTask的生成优先使用setImmediateMessageChannel而不是setTimeout,原因是setTimeout默认的最小延迟时间是4ms,前两者的延迟明显是小于这个数值的。
    所以执行时机不同的原因就是因为timerFunc的实现方式不同,如果是PromiseMutationObservernextTickHandler执行调用的是一个microTask,他会在当前Tick的末尾执行,反之会在下一个Tick的时候执行。

    总结:

    nextTick是一个自执行函数,所以调用nextTick时就相当于调用了queueNextTick,这个函数就会被存放到callbacks的闭包中,然后这个callbacksnextTickHandler执行,执行时间又由timerFunc决定。

    问题解决:

    Vue2.4版本之前,nextTick几乎都是基于microTask实现的,但是由于它的优先级很高甚至高于冒泡,就会导致一些问题,比如一个添加了click事件的chekbox不能选中,input框的内容在事件触发的时候没有正确更新等,但是全部用 macrotask又会对一些重绘和动画的场景有影响,所以nextTick最终是默认走microTask,但是对于一些DOM交互事件会强制走macrotask
    v-on 绑定的事件回调函数的处理,会强制走 macrotask,做法是Vue.js在绑定DOM事件的时候,默认会给handler函数调用withMacroTask方法做一层包装,他能保证整个回调函数执行的时候一旦遇到状态改变,就会被推入到macrotask中。
    macrotask的执行,Vue首先检测是否支持原生的setImmediateMessageChannel,最后都不支持才会选择setTimeout

    var vm = new Vue({
        el: '#example',
        data: {
            msg: 'begin',
        },
        mounted () {
          this.msg = 'end'
          console.log('1')
          setTimeout(() => { // macroTask
             console.log('3')
          }, 0)
          Promise.resolve().then(function () { //microTask
            console.log('promise')
          })
          this.$nextTick(function () {
            console.log('2')
          })
      }
    })
    

    上面代码正常情况下,会打印1->promise->2->3,这是因为首先this.msg = 'end'触发了watcherupdate,从而将更新操作的回调push进vue的事件队列里面,this.$nextTick也会push进一个回调函数,他们都会通过setImmediate-MessageChannel-Promise-setTimeout的优先级定义timeFunc。而Promise是微任务,所以会优先打印。
    但是在浏览器不支持setImmediateMessageChannel的情况下,就会通过Promise来定义timeFunc,所以此时的打印顺序就会变成1->2->promise->3。

    nextTick对audio播放的影响:

    歌曲的播放是用vuex进行状态管理的,正在播放的列表playlist和当前播放索引currentIndex都用state来维护,当前播放歌曲currentSong就是由他们计算而来的。然后通过watchcurrentSong的变化来播放歌曲。

    const state = {
      playlist: [],
      currentIndex:0
    }
    // getters.js
    export const currentSong = (state) => {
      return state.playlist[state.currentIndex] || {}
    }
    
    watch : {
       currentSong(newSong,oldSong) {
          if (!newSong.id || !newSong.url || newSong.id === oldSong.id) {
              return
           }
           this.$refs.audio.src = newSong.url
           this.$refs.audio.play()
       }
    }
    

    从上面的分析我们知道,watcher的回调函数执行是异步的,当我们提交对playlist或者currentIndex的修改,都会触发currentSong的变化,但是watcher的回调函数并不会立刻执行,而是在nextTick之后执行。即,用户点击歌曲和歌曲的播放并不是在一个tick中完成的。所以把 Vue.js 降级到 2.4+ 就可以了,因为 Vue.js 2.5 之前的 nextTick 都是优先使用 microtask 的,那么 audio 播放的时机实际上还是在当前 tick,所以当然不会有问题。(2.5之后是默认走microtask,对于一些DOM交互事件会强制走macroTask) 。
    参考文章:
    https://segmentfault.com/a/1190000013314893
    https://www.cnblogs.com/tiedaweishao/p/8967127.html
    https://juejin.im/post/5a1af88f5188254a701ec230#heading-10

    相关文章

      网友评论

          本文标题:nextTick的问题

          本文链接:https://www.haomeiwen.com/subject/ojbzgctx.html