Vue2 原始碼漫遊(二)

daipeng7發表於2017-11-14

Vue2 原始碼漫遊(二)

描述:

    在(一)中其實已經把Vue作為MVVM的框架中資料流相關跑了一遍。這一章我們先看mount這一步,這樣Vue大的主線就基本跑通了。然後我們再去看compile,v-bind等功能性模組的處理。

一、出發點

path:
    platformswebentry-runtime-with-compiler.js
這裡對原本的公用$mount方法進行了代理.實際的直接方法是core/instance/lifecycle.js中的mountComponent方法。
根據元件模板的不同形式這裡出現了兩個分支,一個核心:
    分支:
        1、元件引數中有render屬性:執行mount.call(this, el, hydrating)
        2、元件引數中沒有render屬性:將template/el轉換為render方法
    核心:Vue.prototype._render公共方法
/* @flow */

import config from `core/config`
import { warn, cached } from `core/util/index`
import { mark, measure } from `core/util/perf`

import Vue from `./runtime/index`
import { query } from `./util/index`
import { compileToFunctions } from `./compiler/index`
import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from `./util/compat`

const idToTemplate = cached(id => {
  const el = query(id)
  return el && el.innerHTML
})
//這裡代理了vue例項的$mount方法
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)

  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== `production` && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

  const options = this.$options
  // resolve template/el and convert to render function
  //解析template/el轉化為render方法。這裡就是一個大的分支,我們可以將它稱為render分支
  if (!options.render) {
    //如果沒有傳入render方法,且template引數存在,那麼就開始解析模板,這就是compile的開始
    let template = options.template
    if (template) {
      if (typeof template === `string`) {
        if (template.charAt(0) === `#`) {
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== `production` && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== `production`) {
          warn(`invalid template option:` + template, this)
        }
        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== `production` && config.performance && mark) {
        mark(`compile`)
      }

      const { render, staticRenderFns } = compileToFunctions(template, {
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
      if (process.env.NODE_ENV !== `production` && config.performance && mark) {
        mark(`compile end`)
        measure(`vue ${this._name} compile`, `compile`, `compile end`)
      }
    }
  }
  //呼叫公用mount方法
  return mount.call(this, el, hydrating)
}

/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */
function getOuterHTML (el: Element): string {
  if (el.outerHTML) {
    return el.outerHTML
  } else {
    const container = document.createElement(`div`)
    container.appendChild(el.cloneNode(true))
    return container.innerHTML
  }
}

Vue.compile = compileToFunctions

export default Vue

1、元件中有render屬性

//最常見
new Vue({
    el: `#app`,
    router,
    render: h => h(App),
});

如果有render方法,那麼就會呼叫公共mount方法,然後判斷一下平臺後直接呼叫mountComponent方法

// public mount method
//入口中被代理的公用方法就是它,path : platformsweb
untimeindex.js
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  //因為是公用方法所以在這裡有重新判斷了一些el,其實如果有render屬性的話,這裡el就已經是DOM物件了
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

接下來就是mountComponent。這裡面有一個關鍵點 vm._watcher = new Watcher(vm, updateComponent, noop),這個其實就是上篇中說到的依賴收集的一個觸發點。你可以想想,元件在這個時候其實資料已經完成了響應式轉換,就坐等收集依賴了,也就是坐等被第一次使用訪問了。

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  //這個判斷其實只是在配置預設render方法createEmptyVNode
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode
    if (process.env.NODE_ENV !== `production`) {
      /* istanbul ignore if */
      if ((vm.$options.template && vm.$options.template.charAt(0) !== `#`) ||
        vm.$options.el || el) {
        warn(
          `You are using the runtime-only build of Vue where the template ` +
          `compiler is not available. Either pre-compile the templates into ` +
          `render functions, or use the compiler-included build.`,
          vm
        )
      } else {
        warn(
          `Failed to mount component: template or render function not defined.`,
          vm
        )
      }
    }
  }
  //執行beforeMount回撥函式
  callHook(vm, `beforeMount`)

  //這個updateComponent方法很重要,其實可以將它與Watcher中的引數expOrFn聯絡起來。他就是一個Watcher例項的值的獲取過程,訂閱者的一種真實身份。
  let updateComponent
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== `production` && config.performance && mark) {
    updateComponent = () => {
      const name = vm._name
      const id = vm._uid
      const startTag = `vue-perf-start:${id}`
      const endTag = `vue-perf-end:${id}`

      mark(startTag)
      const vnode = vm._render()
      mark(endTag)
      measure(`vue ${name} render`, startTag, endTag)

      mark(startTag)
      vm._update(vnode, hydrating)
      mark(endTag)
      measure(`vue ${name} patch`, startTag, endTag)
    }
  } else {
    updateComponent = () => {
      //實際方法,被Watcher.getter方法的執行給呼叫回來了,在這裡先直接執行vm.render,這個就是compile的觸發點
      vm._update(vm._render(), hydrating)
    }
  }
  //開始生產updateComponent這個動作的訂閱者了,生產過程中呼叫Watcher.getter方法時又會回來執行這個updateComponent方法。看上面兩排
  vm._watcher = new Watcher(vm, updateComponent, noop)
  hydrating = false

  // manually mounted instance, call mounted on self
  // mounted is called for render-created child components in its inserted hook
  if (vm.$vnode == null) {
    vm._isMounted = true
    callHook(vm, `mounted`)
  }
  return vm
}

2、公共render方法

path : coreinstance
ender.js
Vue.prototype._render()這個方法的呼叫在整個原始碼中就兩處,vm._render()和child._render()。
從中可以理解到一個執行鏈條:

$mount -> new Watcher -> watcher.getter -> updateComponent -> vm._update -> vm._render -> vm.createElement -> createComponent(如果存在子元件,呼叫createElement,如果沒有執行createElement)
在render的這一個層面上的出發點,都是來自於vm.$options.render函式,這也是為什麼在Vue.prototype.$mount方法中會對vm.$options.render進行判斷處理從而分出有render函式和沒有render函式兩種不同的處理方式

看一下vm._render原始碼:


export function renderMixin (Vue: Class<Component>) {
  // install runtime convenience helpers
  installRenderHelpers(Vue.prototype)

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

  Vue.prototype._render = function (): VNode {
    const vm: Component = this
    const { render, _parentVnode } = vm.$options
    
    //如果父元件還沒有更新,那麼就先把子元件存在vm.$slots中
    if (vm._isMounted) {
      // if the parent didn`t update, the slot nodes will be the ones from
      // last render. They need to be cloned to ensure "freshness" for this render.
      for (const key in vm.$slots) {
        const slot = vm.$slots[key]
        if (slot._rendered) {
          vm.$slots[key] = cloneVNodes(slot, true /* deep */)
        }
      }
    }
    //作用域插槽
    vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject

    // set parent vnode. this allows render functions to have access
    // to the data on the placeholder node.
    vm.$vnode = _parentVnode
    // render self
    let vnode
    try {
      //執行$options.render,如果沒傳的就是一個預設的VNode例項。最後都會去掉用createElement公用方法corevdomcreate-element.js。這個就是大工程了。
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      handleError(e, vm, `render`)
      // return error render result,
      // or previous vnode to prevent render error causing blank component
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== `production`) {
        if (vm.$options.renderError) {
          try {
            vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
          } catch (e) {
            handleError(e, vm, `renderError`)
            vnode = vm._vnode
          }
        } else {
          vnode = vm._vnode
        }
      } else {
        vnode = vm._vnode
      }
    }
    // return empty vnode in case the render function errored out
    if (!(vnode instanceof VNode)) {
      if (process.env.NODE_ENV !== `production` && Array.isArray(vnode)) {
        warn(
          `Multiple root nodes returned from render function. Render function ` +
          `should return a single root node.`,
          vm
        )
      }
      vnode = createEmptyVNode()
    }
    // set parent
    vnode.parent = _parentVnode
    return vnode
  }
}

3、_createElement, createComponent


path : corevdomcreate-element.js
_createElement(context, tag, data, children, normalizationType)
export function _createElement (
  context: Component,
  tag?: string | Class<Component> | Function | Object,
  data?: VNodeData,
  children?: any,
  normalizationType?: number
): VNode {
  //可以使用
  if (isDef(data) && isDef((data: any).__ob__)) {
    process.env.NODE_ENV !== `production` && warn(
      `Avoid using observed data object as vnode data: ${JSON.stringify(data)}
` +
      `Always create fresh vnode data objects in each render!`,
      context
    )
    return createEmptyVNode()
  }
  // object syntax in v-bind
  if (isDef(data) && isDef(data.is)) {
    tag = data.is
  }
  if (!tag) {
    // in case of component :is set to falsy value
    return createEmptyVNode()
  }
  // warn against non-primitive key
  if (process.env.NODE_ENV !== `production` &&
    isDef(data) && isDef(data.key) && !isPrimitive(data.key)
  ) {
    warn(
      `Avoid using non-primitive value as key, ` +
      `use string/number value instead.`,
      context
    )
  }
  // support single function children as default scoped slot
  if (Array.isArray(children) &&
    typeof children[0] === `function`
  ) {
    data = data || {}
    data.scopedSlots = { default: children[0] }
    children.length = 0
  }
  if (normalizationType === ALWAYS_NORMALIZE) {
    children = normalizeChildren(children)
  } else if (normalizationType === SIMPLE_NORMALIZE) {
    children = simpleNormalizeChildren(children)
  }
  let vnode, ns
  if (typeof tag === `string`) {
    let Ctor
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
      // platform built-in elements
      vnode = new VNode(
        config.parsePlatformTagName(tag), data, children,
        undefined, undefined, context
      )
    } else if (isDef(Ctor = resolveAsset(context.$options, `components`, tag))) {
      // component
      vnode = createComponent(Ctor, data, context, children, tag)
    } else {
      // unknown or unlisted namespaced elements
      // check at runtime because it may get assigned a namespace when its
      // parent normalizes children
      vnode = new VNode(
        tag, data, children,
        undefined, undefined, context
      )
    }
  } else {
    // direct component options / constructor
    vnode = createComponent(tag, data, context, children)
  }
  if (isDef(vnode)) {
    if (ns) applyNS(vnode, ns)
    return vnode
  } else {
    return createEmptyVNode()
  }
}
    path : corevdomcreate-component.js
    createComponent (Ctor, data, context, children, tag)
        Ctor : 元件Module資訊,最後與會被處理成vm例項物件
        data : 元件資料
        context : 當前Vue元件
        children : 自元件
        tag :元件名
const hooksToMerge = Object.keys(componentVNodeHooks)

export function createComponent (
  Ctor: Class<Component> | Function | Object | void,
  data: ?VNodeData,
  context: Component,
  children: ?Array<VNode>,
  tag?: string
): VNode | void {

  //Ctor不能為undefined || null
  if (isUndef(Ctor)) {
    return
  }
  //
  const baseCtor = context.$options._base

  // plain options object: turn it into a constructor
  // 如果Ctor為物件,合併到vm資料,構建Ctor
  if (isObject(Ctor)) {
    Ctor = baseCtor.extend(Ctor)
  }

  // if at this stage it`s not a constructor or an async component factory,
  // reject.
  if (typeof Ctor !== `function`) {
    if (process.env.NODE_ENV !== `production`) {
      warn(`Invalid Component definition: ${String(Ctor)}`, context)
    }
    return
  }

  // 非同步元件
  let asyncFactory
  if (isUndef(Ctor.cid)) {
    asyncFactory = Ctor
    Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context)
    if (Ctor === undefined) {
      // return a placeholder node for async component, which is rendered
      // as a comment node but preserves all the raw information for the node.
      // the information will be used for async server-rendering and hydration.
      return createAsyncPlaceholder(
        asyncFactory,
        data,
        context,
        children,
        tag
      )
    }
  }

  data = data || {}

  // resolve constructor options in case global mixins are applied after
  // component constructor creation
  //解析元件例項的options
  resolveConstructorOptions(Ctor)

  // transform component v-model data into props & events
  if (isDef(data.model)) {
    transformModel(Ctor.options, data)
  }

  // extract props
  const propsData = extractPropsFromVNodeData(data, Ctor, tag)

  // functional component
  if (isTrue(Ctor.options.functional)) {
    return createFunctionalComponent(Ctor, propsData, data, context, children)
  }

  // extract listeners, since these needs to be treated as
  // child component listeners instead of DOM listeners
  const listeners = data.on
  // replace with listeners with .native modifier
  // so it gets processed during parent component patch.
  data.on = data.nativeOn

  if (isTrue(Ctor.options.abstract)) {
    // abstract components do not keep anything
    // other than props & listeners & slot

    // work around flow
    const slot = data.slot
    data = {}
    if (slot) {
      data.slot = slot
    }
  }

  // merge component management hooks onto the placeholder node
  // 合併鉤子函式 init 、 destroy  、 insert 、prepatch
  mergeHooks(data)

  // return a placeholder vnode
 // 最終目的生成一個vnode,然後就是一路的return出去
  const name = Ctor.options.name || tag
  const vnode = new VNode(
    `vue-component-${Ctor.cid}${name ? `-${name}` : ``}`,
    data, undefined, undefined, undefined, context,
    { Ctor, propsData, listeners, tag, children },
    asyncFactory
  )
  return vnode
}

總結:

過程線條:

$mount -> new Watcher -> watcher.getter -> updateComponent -> vm._update -> vm._render -> vm.createElement -> createComponent(如果存在子元件,呼叫createElement,如果沒有執行createElement)

上面這個線條中其實都圍繞著vm.$options進行render元件。現在大部分專案都是使用的.vue元件進行開發,所以使得對元件的配置物件不太敏感。
因為將.vue的內容轉化為Vue元件配置模式的過程都被vue-loader處理(我們在require元件時處理的),其中就包括將template轉換為render函式的關鍵。我們也可以定義一個配置型的元件,然後觸發Vue$3.prototype.$mount中的mark(`compile`)進行處理。但是我覺得意義不是太大。
過程,這也是導致我們在原始碼執行中總是看見在有無render函式分支,的時候總是能看見render函式,然後就進入對元件 vm._update(vm._render(), hydrating)。
我們先記住這條主線,下一章我們進入到vue-loader中去看看

相關文章