深入浅出Vue.nextTick

痞子三分冷 提交于 2020-05-09 12:56:29

nextTick是什么

Vue的官方文档中这么说的:“在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。”,为什么会出现这么一个API?主要原因是因为Vue在更新DOM采用的是异步执行的,只要侦听到数据变化,Vue将开启一个队列,并缓冲在同一个事件循环中发生的所有数据变更。

使用场景

虽然官方一直建议我们使用数据驱动的方案去写代码,但是偶尔还是不可避免的需要操作dom。

<div v-for='item of list' :key='item' class='list-item'>
  {{ item }}
</div>
list = [1,2,3,4]
当我们在mounted中往list中push一个数字的时候,立刻获取class='list-item'元素的长度,拿到的依然是4,并没有变成5。
因为Vue中DOm更新是异步,所以立刻打印DOM并没有更新,这时候通过nextTick才能正确的获得长度。

this.$nextTick(() => {
    console.log(document.getElementByClassName('list-item').length)
})
复制代码

如果一个事件循环中多次改变状态怎么处理?

如果同一个 watcher 被多次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作是非常重要的。然后,在下一个的事件循环“tick”中,Vue 刷新队列并执行实际 (已去重的) 工作,总的来说就是去重,内部具体是什么样的,等我看了再告诉你们。

事件循环

我们都是知道JS是单线程非阻塞的语言,这意味着主线程只能一次性执行一个任务 首先了解一下基本概念:微任务,宏任务,异步任务,同步任务。

微任务

微任务,microtask 又叫jobs,常见的有: 1.process.nextTick(node) 2.Promise 3.MutationObserver(HTML5新特性) 4.Mess

宏任务

宏任务,macroTask 又叫task,常见的有: 1.script(整体代码) 2.setTimeout 3.setInterval 4.setImmediate 5.I/O 6.UI render 7.MessageChannel

同步任务

指的是,在主线程上排队执行的任务,只有前一个任务执行完毕,才能执行后一个任务,例如 1+2,典型的案例


function loop() {
    while(true) {}
}
loop()

console.log(1)
复制代码

执行loop会占用主线程,进入无限循环,前面没执行完,后面的1一直不会被打印

异步任务

指的是,不进入主线程、而进入"任务队列"(task queue)的任务,只有等主线程任务执行完毕,"任务队列"开始通知主线程,请求执行任务,该任务才会进入主线程执行,

function loop () {
    setTimeout(loop, 0);
}
loop()
复制代码

执行loop的时候。看似是一个无限循环的状态,但是实际上,不会导致页面卡死,依然可以做其他的事情,因为setTimeout是一个异步任务,他们执行完一次就会退出主线程。

event-loop是什么

event-loop

这张图将浏览器的Event Loop完整的描述了出来,我来讲执行一个JavaScript代码的具体流程 在执行一段代码的时候,先执行同步任务,再执行微任务,再执行宏任务; 1.执行全局Script同步代码,这些同步代码有一些是同步语句,有一些是异步语句(比如setTimeout等); 2.全局Script代码执行完毕后,调用栈Stack会清空; 3.从微队列microtask queue中取出位于队首的回调任务,放入调用栈Stack中执行,执行完后microtask queue长度减1; 4.继续取出位于队首的任务,放入调用栈Stack中执行,以此类推,直到直到把microtask queue中的所有任务都执行完毕。注意,如果在执行microtask的过程中,又产生了microtask,那么会加入到队列的末尾,也会在这个周期被调用执行; 5.microtask queue中的所有任务都执行完毕,此时microtask queue为空队列,调用栈Stack也为空; 6.取出宏队列macrotask queue中位于队首的任务,放入Stack中执行; 7.执行完毕后,调用栈Stack为空; 重复第3-7个步骤;(event-loop)

探究下nextTick的实现原理

前面说过了,因为Vue在更新DOM采用的是异步执行的,只要侦听到数据变化,Vue将开启一个队列,并缓冲在同一个事件循环中发生的所有数据变更。所以我们只需要把要执行的callback放到微任务或者宏任务中去执行,就可以了。

按照这个思路我们去看下Vue中的实现:

1.首先有个callbacks的队列 2.多次使用nextTick只算一次,所以需要使用pending限制一下,否则页面看到的就是一个连续变化的过程,体验很不好 3.根据不同的平台,浏览器环境,向下兼容,兜底方案是setTimeout 4.顺序是这样子的:Promise > MutationObserver > setImmediate > setTimeout

源码

/* @flow */
/* globals MutationObserver */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'

// 此处标记是否为微任务,会在其他模块中,对事件做特殊处理
export let isUsingMicroTask = false

// 回掉队列
const callbacks = []

// =============================
// 状态标记,只执行一次
let pending = false

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc

// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */

if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  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)
  }
}

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


  // 作为一个 Promise 使用 (2.1.0 起新增)
  // 2.1.0 起新增:如果没有提供回调且在支持 Promise 的环境中,
  // 则返回一个 Promise。请注意 Vue 不自带 Promise 的 polyfill,所以如果你的目标浏览器不原生支持 Promise (IE:你们都看我干嘛),你得自己提供 polyfill。
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

复制代码

最后周末愉快

参考文章

1.带你彻底弄懂Event Loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!