了解nextTick,需要了解事件循环机制

723 阅读4分钟

这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战

是什么?

下次DOM更新循环结束之后执行延迟回调,在修改数据之后使用$nextTick,则可以在回调中获取更新后的DOM

为什么要用?

官方解释:

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

例:当你设置this.someData = “new value”,该组件不会重新渲染。当刷新队列,组件会在下一个事件循环”tick”中更新。多数情况我们不需要关心这个过程

怎么做?

var vm = new Vue({
    el: '#app',
    data: {
        message: '123'
    }
})
vm.message = 'new message' //更改数据
vm.$el.textContent === 'new message' //false
Vue.nextTick(function () {
    vm.$el.textContent === 'new message' // true
})
//组件中使用
this.$nextTick(() => {
    
})

textContent和innerText的区别,兼容性,前者IE8不支持

因为$nextTick()返回一个Promise对象,所以可以使用async/await语法完成相同的事

updateMessage: async function () {
    this.message = "已更新"
    console.log(this.$el.textContent) // =>未更新
    await this.$nextTick()
    console.log(this.$el.textContent)// => 已更新
}

浏览器的线程 GUI渲染线程 JS引擎线程 事件触发线程 (EventLoop) 定时出发器线程 异步HTTP请求线程

GUI渲染线程JS引擎线程是互斥的

Event loop机制

执行栈

堆里存放着一些对象。

栈里存放着一些基础类型变量以及对象的指针

js在执行可执行的脚本时,首先会创建一个全局可执行上下文globalContext,每当执行到一个函数调用时都会创建一个可执行上下文(execution context)EC。当然可执行程序可能会存在很多函数调用,那么就会创建很多EC,所以JavaScrpt引擎创建了执行上下文栈(Execution context stack,ECS)来管理执行上下文。当函数调用完成,js会退出这个执行环境并把这个执行环境销毁,回到上一个方法的执行环境,这个过程反复进行,直到执行栈中的代码全部执行完毕

事件队列

以上过程说的都是同步代码的执行。那么当一个异步代码(如发送ajax请求数据)执行后会如何呢?接下来需要了解另一个概念就是:事件队列(Task Queue)。

浏览器为了能够使得JS引擎线程GUI渲染线程有序切换,会在当前宏任务结束之后,下一个宏任务执行开始之前,对页面进行重新渲染

宏任务 -> 微任务 -> 渲染 -> 宏任务 -> 微任务 -> 渲染 。。。

当js引擎遇到一个异步事件后,其实不会说一直等到异步事件的返回,而时先将异步事件进行挂起。等到异步事件执行完毕后,会被加入到事件队列中。(注意,此时只是异步事件执行完成,其中的回调函数并没有取执行。)当执行队列执行完成,主线程处于闲置状态时,会去异步队列那抽取最先被推入队列中的异步事件,放入执行栈中,执行其中的回调同步代码。如此反复,这样就形成了一个无限的循环。这就是这个过程被称为“事件循环(Event Loop)”的原因

宏任务

script (主代码块)、MessageChannel、postMessage、setImmediate、I/O 、UI rendering

setTimeout(setTimeout的含义是,指定某个任务在主线程最早可得的空闲时间执行,也就是说,尽可能早的执行。它在“任务队列”的尾部添加一个事件,因此要等到同步任务和“任务队列”现有的事件处理完,才会得到执行。需要注意的是,setTimeout只是将事件插入了“任务队列“,必须等到当前代码执行完,主线程才会去执行它指定的回调函数。要是当前代码耗时很长,有可能要等很久,所以并没有办法保证,回调函数一定会在setTimeout指定的时间执行)

微任务

new Promise()、new MutaionObserver()、process.nextTick(Nodejs)

在一个事件循环中,异步事件返回结果会被放入到一个任务队列中。然而根据这个异步事件的类型,这个事件实际会被对应的宏任务队列或者微任务队列中去。并且在当前执行栈为空的时候,主线程会查看微任务队列是否有事件存在。如果不存在,那么再去宏任务队列中取出一个事件并把对应的回到加入当前执行栈;如果存在,则会一次执行队列中事件对应的回调,直到微任务队列为空,然后去宏任务队列中取出最前面的一个事件,把对应的回调加入当前执行栈。。。如此反复,进入循环。

nextTick源码:

/* @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
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}