{{message}}</div>var...">
最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • nextTick 解析

    正文概述 掘金(Des bisous)   2021-02-28   654

    前言

    以下是使用 vue 的经常使用到 nextTick 的一个场景:

    <!--Html-->
    <div id="example">{{message}}</div>
    
    var vm = new Vue({
      el: '#example',
      data: {
        message: '123'
      }
    })
    vm.message = 'new message' // 更改数据
    vm.$el.textContent === 'new message' // false
    Vue.nextTick(function () {
      vm.$el.textContent === 'new message' // true
    })
    

    这个例子是 vue2.x 官方演示案例,许多的开发者都知道这个的用法,但是为什么这样使用就能拿到最新变更后新的 dom 呢?

    因此本人带着好奇心翻阅了源码,以此做下记录。

    源码分析

    首先我们使用 nextTick 的时候,一般都进行了数据变更,比如案例中的:vm.message = 'new message',那从这边一步开始看,数据变更必然触发数据劫持后的 set 方法,并且 notify,以此进入到 notify 方法:

    路径:vue/src/core/observer/dep.js

    notify () {
        // stabilize the subscriber list first
        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()
        }
      }
    }
    

    notify 方法对数据所依赖的更新函数进行遍历执行,以此进入 update 方法:

    路径:vue/src/core/observer/watcher.js

    update () {
        /* istanbul ignore else */
        if (this.lazy) {
          this.dirty = true
        } else if (this.sync) {
          this.run()
        } else {
          queueWatcher(this)
        }
    }
    

    update 做了几个判断, 是否 lazy 这个如果是 computed 的话,会设置 dirty,还有是否 sync,这种就直接执行,最后就是我们要说的,vue 更新 state 的时候是异步的,就是因为这里进行了一个队列的收集,而不是变更了 state 数据马上进行更新视图,看看 queueWatcher 做了什么:

    路径:

    /**
     * Push a watcher into the watcher queue.
     * Jobs with duplicate IDs will be skipped unless it's
     * pushed when the queue is being flushed.
     */
    export function queueWatcher (watcher: Watcher) {
      const id = watcher.id
      if (has[id] == null) {
        has[id] = true
        if (!flushing) {
          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 = true
    
          if (process.env.NODE_ENV !== 'production' && !config.async) {
            flushSchedulerQueue()
            return
          }
          nextTick(flushSchedulerQueue)
        }
      }
    }
    

    将变更后的依赖更新函数,放入到了 queue 中,然后进行了调度,其中看到最后异步,执行了 nextTick(flushSchedulerQueue) 这时候是不是疑惑,难道这个 nextTick 就是我们在代码中所使用的的 vm。nextTick 没错,源码中这里也一样是使用了这个方法,来看看 nextTick 做了什么:

    路径:vue/src/core/util/next-tick.js

    export function nextTick (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 => {
          _resolve = resolve
        })
      }
    }
    

    可以看到,它将更新函数传入 push 到了 callbacks 中,并执行了 timeFunc 这是 nextTick 的核心函数:

    路径:vue/src/core/util/next-tick.js

    timerFunc = () => {
        p.then(flushCallbacks)
        // In problematic UIWebViews, Promise.then doesn't completely break, but
        // it can get stuck in a weird state where callbacks are pushed into the
        // microtask queue but the queue isn't being flushed, until the browser
        // needs to do some other work, e.g. handle a timer. Therefore we can
        // "force" the microtask queue to be flushed by adding an empty timer.
        if (isIOS) setTimeout(noop)
      }
      isUsingMicroTask = true
    } else if (!isIE && typeof MutationObserver !== 'undefined' && (
      isNative(MutationObserver) ||
      // PhantomJS and iOS 7.x
      MutationObserver.toString() === '[object MutationObserverConstructor]'
    )) {
      // Use MutationObserver where native Promise is not available,
      // e.g. PhantomJS, iOS7, Android 4.4
      // (#6466 MutationObserver is unreliable in IE11)
      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)) {
      // Fallback to setImmediate.
      // Technically it leverages the (macro) task queue,
      // but it is still a better choice than setTimeout.
      timerFunc = () => {
        setImmediate(flushCallbacks)
      }
    } else {
      // Fallback to setTimeout.
      timerFunc = () => {
        setTimeout(flushCallbacks, 0)
      }
    }
    

    看到 timerFunc 就可以明白了,在进行数据变更的时候什么时候进行 dom 的更新,它将更新时间交给了:

    • Promise.then
    • MutationObserver
    • setImmediate
    • setTimeout

    以上四个机制进行处理,按照以上到下的优先级使用,做了兼容性,前两个是异步微任务,后两个是异步宏任务。

    关于微任务和宏任务不了解的可阅读另一篇文章:链接

    关于 MutationObserver 的使用可阅读另一篇文章:链接

    再次就可了解到,在 vue 更新 state 数据的时候,是进行了批量入队列,然后开启异步任务处理的,所以像:

    vm.message = 'new message' // 更改数据
    vm.$el.textContent === 'new message' // false
    

    这样变更后马上获取 dom 的 textContent 当人是无法获取到最新的,因为这时候更新 dom 的任务还未开始,因此应该明白以下步骤

    vm.message = 'new message' // 更改数据
    Vue.nextTick(function () {
      vm.$el.textContent === 'new message' // true
    })
    

    为什么可以获取到最新 dom 了,因为这时候,同样执行了 nextTick 方法,传入回调开启异步任务,然而这个异步任务是微任务,在当前帧中进入队列的微任务会在当前 loop event 中一同执行,也就是在变更数据后所依赖的更新函数的微任务执行之后紧跟着就会执行代码中写的:

    Vue.nextTick(function () {
      vm.$el.textContent === 'new message' // true
    })
    

    这个任务了,所以这时候可以拿到最新的 dom 数据。


    起源地下载网 » nextTick 解析

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元