Vue.js 2.0 源码分析 nextTick、use与mixin

145 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

3.nextTick

js的执行是单线程的,主线程的执行过程就是一个tick,而所有的异步结果都是通过 “任务队列” 来调度,这其中就涉及到了宏任务与微任务,在浏览器环境中,常见的 macro task 有 setTimeout、MessageChannel、postMessage、setImmediate;常见的 micro task 有 MutationObsever 和 Promise.then,这里不做赘述。 接下来看nextTick源码:

const callbacks = []
let pending = false
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
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

首先抛弃_resolve的逻辑(这是为实现promise而准备的,下文会提到), 该函数首先会向callbacks数组中推入一个匿名函数,(如果调用了多次nextTick函数则向callbacks数组中推入多个匿名函数),该匿名函数执行的时候会触发传入的callback(也就是调用时候定义的cb),再判断pending,这个pending刚开始的时候是false,进入后赋值为true,也就确保这个逻辑只会执行一次,再判断useMacroTask,根据浏览器的支持,确定不同的执行方式(确定使用哪种方式执行下一个tick)。

// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false

// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. 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)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  // PhantomJS
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  microTimerFunc = () => {
    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)
  }
} else {
  // fallback to macro
  microTimerFunc = macroTimerFunc
}

/**
 * Wrap a function so that if any code inside triggers state change,
 * the changes are queued using a (macro) task instead of a microtask.
 */
export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    const res = fn.apply(null, arguments)
    useMacroTask = false
    return res
  })
}

可以看到会优先检测浏览器是否支持原生 setImmediate,不支持的话再去检测是否支持原生的MessageChannel,如果也不支持的话就会降级为 setTimeout 0;而对于 micro task 的实现,则检测浏览器是否原生支持 Promise,不支持的话直接指向 macro task 的实现,而这些函数其实最终都是会执行flushCallbacks。

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

可以看到,flushCallbacks中将pending赋值为了false,再依次执行了下一个tick中的所有的callback(我们传入了多少个回调函数,都会收集在一个tick中执行完)。 此外,回到_resolve变量,除了传入回调的方式外,nextTick也支持promise.then,当没有cb传入的时候,会执行:

if (!cb && typeof Promise !== 'undefined') {
  return new Promise(resolve => {
    _resolve = resolve
  })
}

在下一个tick执行的时候则会走到else if逻辑,也就可以通过.then的方式去执行。

if (cb) {
  try {
     cb.call(ctx)
   } catch (e) {
     handleError(e, ctx, 'nextTick')
   }
} else if (_resolve) {
   _resolve(ctx)
}

由以上可知,nextick函数也就是将所有的回调函数收集放在下一个tick中去执行的。

$nextTick

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

在构造函数Vue的原型上也挂载了nextTick方法,这就是我们为什么也可以使用this.$nextTick去调用nextTick的原因。

4.use、mixin

Vue.use与mixin的源码大家可以去看我的另一篇源码分析从初始化vuex的角度分析use、mixin,里面通过对Vue.use(Store)过程的分析,对use、mixin的理解更形象具体。 对于use函数,其实核心就是执行了传入的插件的install方法:

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > -1) {
      return this
    }

    // additional parameters
    const args = toArray(arguments, 1)
    args.unshift(this)
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin)
    return this
  }
}

对于mixin函数,核心是执行了mergeOptions函数,也就是向Vue.options添加mixin对象

export function initMixin (Vue: GlobalAPI) {
  Vue.mixin = function (mixin: Object) {
    this.options = mergeOptions(this.options, mixin)
    return this
  } 
}

其中,mergeOptions函数中对于不同的属性有不同的合并策略,比如钩子函数

/**
 * Merge two option objects into a new one.
 * Core utility used in both instantiation and inheritance.
 */
export function mergeOptions (
  parent: Object,
  child: Object,
  vm?: Component
): Object {
  if (process.env.NODE_ENV !== 'production') {
    checkComponents(child)
  }

  if (typeof child === 'function') {
    child = child.options
  }

  normalizeProps(child, vm)
  normalizeInject(child, vm)
  normalizeDirectives(child)
  const extendsFrom = child.extends
  if (extendsFrom) {
    parent = mergeOptions(parent, extendsFrom, vm)
  }
  if (child.mixins) {
    for (let i = 0, l = child.mixins.length; i < l; i++) {
      parent = mergeOptions(parent, child.mixins[i], vm)
    }
  }
  const options = {}
  let key
  for (key in parent) {
    mergeField(key)
  }
  for (key in child) {
    if (!hasOwn(parent, key)) {
      mergeField(key)
    }
  }
  function mergeField (key) {
    const strat = strats[key] || defaultStrat
    options[key] = strat(parent[key], child[key], vm, key)
  }
  return options
}
LIFECYCLE_HOOKS.forEach(hook => {
  strats[hook] = mergeHook
})
function mergeHook (
  parentVal: ?Array<Function>,
  childVal: ?Function | ?Array<Function>
): ?Array<Function> {
  return childVal
    ? parentVal
      ? parentVal.concat(childVal)
      : Array.isArray(childVal)
        ? childVal
        : [childVal]
    : parentVal
}

对于钩子函数,会通过parentVal.concat(childVal)合并为一个数组混合到Vue.options对象上,执行顺序是从前到后。

if (child.mixins) {
  for (let i = 0, l = child.mixins.length; i < l; i++) {
    parent = mergeOptions(parent, child.mixins[i], vm)
  }
}

对于传入的mixin对象有mixins属性的情况下,先将mixins属性中的钩子函数合并到parent后面,再合并mixin对象中的钩子函数,最终的执行顺序为: Vue.options上面的钩子函数-->mixin对象上mixins属性对象上的钩子函数-->mixin对象上的钩子函数。