vue 源码解析 --虚拟Dom-render

instance/index.js

function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}
renderMixin(Vue)

初始化先执行了 renderMixin 方法, Vue 实例化执行this._init, 执行this.init方法中有initRender()node

renderMixin

installRenderHelpers( 将一些渲染的工具函数放在Vue 原型上)数组

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

仔细看这个函数, 在Vue中的官方文档上这样解释promise

Vue 异步执行 DOM 更新。只要观察到数据变化,Vue 将开启一个队列,并缓冲在同一事件循环中发生的全部数据改变。若是同一个 watcher 被屡次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免没必要要的计算和 DOM 操做上很是重要。而后,在下一个的事件循环“tick”中,Vue 刷新队列并执行实际 (已去重的) 工做。Vue 在内部尝试对异步队列使用原生的 Promise.then 和MessageChannel,若是执行环境不支持,会采用 setTimeout(fn, 0)代替。app

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
    })
  }
}

Vue.nextTick用于延迟执行一段代码,它接受2个参数(回调函数和执行回调函数的上下文环境),若是没有提供回调函数,那么将返回promise对象。异步

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

这个flushCallbacks 是执行callbacks里存储的全部回调函数。
timerFunc 用来触发执行回调函数函数

  1. 先判断是否原生支持promise,若是支持,则利用promise来触发执行回调函数;
  2. 不然,若是支持MutationObserver,则实例化一个观察者对象,观察文本节点发生变化时,触发执行
    全部回调函数。
  3. 若是都不支持,则利用setTimeout设置延时为0。
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

MutationObserver是一个构造器,接受一个callback参数,用来处理节点变化的回调函数,observe方法中options参数characterData:设置true,表示观察目标数据的改变工具

_render函数

经过执行 createElement 方法并返回的是 vnode,它是一个虚拟的 Node。优化

vnode = render.call(vm._renderProxy, vm.$createElement)

createElement.js

兼容不传data的状况 以及判断传入的alwaysNormalize是否为true
再调用_createElement函数,能够看到,createElement是对参数作了一些处理之后,将其传给_createElement函数。this

if (Array.isArray(data) || isPrimitive(data)) {
    normalizationType = children
    children = data
    data = undefined
  }
  
  if (isTrue(alwaysNormalize)) {
    normalizationType = ALWAYS_NORMALIZE
  }

建立虚拟节点 _createElement

若是data未定义(undefined或者null)或者是data的__ob__已经被observed,上面绑定了Oberver对象 就建立一个空节点prototype

if (isDef(data) && isDef((data: any).__ob__)) {
    process.env.NODE_ENV !== 'production' && warn(
      `Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
      'Always create fresh vnode data objects in each render!',
      context
    )
    return createEmptyVNode()
  }

主要完成的功能是判断children中的元素是否是数组,若是是的话,就递归调用数组,并将每一个元素保存在数组中返回。

export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}

normalizeArrayChildren 核心代码
先判断children中的元素是否是数组,是的话递归调用函数。若是第一个和最后一个都是文本节点的话,将其合并,优化。判断该元素是否是基本类型。若是是,在判断最后一个结点是否是文本节点,是的话将其与该元素合并为一个文本节点。不然,把这个基本类型转换为文本节点(VNode)最后一种状况,该元素是一个VNode,先一样进行优化(合并第一个和最后一个节点),而后判断该节点的属性,最后将该节点加入到结果中。

if (Array.isArray(c)) {
      if (c.length > 0) {
        c = normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`)
        // merge adjacent text nodes
        if (isTextNode(c[0]) && isTextNode(last)) {
          res[lastIndex] = createTextVNode(last.text + (c[0]: any).text)
          c.shift()
        }
        res.push.apply(res, c)
      }
     
    } else if (isPrimitive(c)) {
      if (isTextNode(last)) {
        // merge adjacent text nodes
        // this is necessary for SSR hydration because text nodes are
        // essentially merged when rendered to HTML strings
        res[lastIndex] = createTextVNode(last.text + c)
      } else if (c !== '') {
        // convert primitive to vnode
        res.push(createTextVNode(c))
      }
    } else {
      if (isTextNode(c) && isTextNode(last)) {
        // merge adjacent text nodes
        res[lastIndex] = createTextVNode(last.text + c.text)
      } else {
        // default key for nested array children (likely generated by v-for)
        if (isTrue(children._isVList) &&
          isDef(c.tag) &&
          isUndef(c.key) &&
          isDef(nestedIndex)) {
          c.key = `__vlist${nestedIndex}_${i}__`
        }
        res.push(c)
      }
    }
相关文章
相关标签/搜索