(六)Vue-模板編譯和組件化

模板編譯

模板編譯的主要目的是將模板 (template) 轉(zhuǎn)換為渲染函數(shù) (render)

  • vue-template-explorer
    Vue 2.6 把模板編譯成 render 函數(shù)的工具
  • vue-next-template-explorer
    Vue 3.0 beta 把模板編譯成 render 函數(shù)的工具

模板編譯過程

編譯的入口

  • src\platforms\web\entry-runtime-with-compiler.js


組件化機制

  1. Vue.component() 入口
  • 創(chuàng)建組件的構(gòu)造函數(shù),掛載到 Vue 實例的vm.options.component.componentName = Ctor
// src\core\global-api\index.js 
// 注冊 Vue.directive()、 Vue.component()、Vue.filter() initAssetRegisters(Vue) 
// src\core\global-api\assets.js 
if (type === 'component' && isPlainObject(definition)) { 
   definition.name = definition.name || id definition = this.options._base.extend(definition) 
}
……
// 全局注冊,存儲資源并賦值 
// this.options['components']['comp'] = Ctor 
this.options[type + 's'][id] = definition 

// src\core\global-api\index.js 
// this is used to identify the "base" constructor to extend all plain- object 
// components with in Weex's multi-instance scenarios. 
Vue.options._base = Vue 

// src\core\global-api\extend.js 
Vue.extend()
  1. 組件構(gòu)造函數(shù)的創(chuàng)建
    const Sub = function VueComponent (options) {
      // 調(diào)用 _init() 初始化
      this._init(options)
    }
    // 原型繼承自 Vue
    Sub.prototype = Object.create(Super.prototype)
    Sub.prototype.constructor = Sub
    Sub.cid = cid++
    // 合并 options
    Sub.options = mergeOptions(
      Super.options,
      extendOptions
    )
    Sub['super'] = Super

    // For props and computed properties, we define the proxy getters on
    // the Vue instances at extension time, on the extended prototype. This
    // avoids Object.defineProperty calls for each instance created.
    if (Sub.options.props) {
      initProps(Sub)
    }
    if (Sub.options.computed) {
      initComputed(Sub)
    }

    // allow further extension/mixin/plugin usage
    Sub.extend = Super.extend
    Sub.mixin = Super.mixin
    Sub.use = Super.use

    // create asset registers, so extended classes
    // can have their private assets too.
    ASSET_TYPES.forEach(function (type) {
      Sub[type] = Super[type]
    })
    // enable recursive self-lookup
    // 把組件構(gòu)造構(gòu)造函數(shù)保存到 Ctor.options.components.comp = Ctor
    if (name) {
      Sub.options.components[name] = Sub
    }

    // keep a reference to the super options at extension time.
    // later at instantiation we can check if Super's options have
    // been updated.
    Sub.superOptions = Super.options
    Sub.extendOptions = extendOptions
    Sub.sealedOptions = extend({}, Sub.options)

    // cache constructor
    // 把組件的構(gòu)造函數(shù)緩存到 options._Ctor
    cachedCtors[SuperId] = Sub
    return Sub
  }

組件創(chuàng)建和掛載

組件 VNode 的創(chuàng)建過程

  • 創(chuàng)建根組件,首次 _render() 時,會得到整棵樹的 VNode 結(jié)構(gòu)
  • 整體流程:new Vue() --> $mount() --> vm._render() --> createElement() --> createComponent()
  • 創(chuàng)建組件的 VNode,初始化組件的 hook 鉤子函數(shù)
// 1. _createElement() 中調(diào)用 createComponent()
// src\core\vdom\create-element.js
    // 判斷是否是 自定義組件
    } else if ((!data || !data.pre) && 
      isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
      // 查找自定義組件構(gòu)造函數(shù)的聲明
      // 根據(jù) Ctor 創(chuàng)建組件的 VNode
      // component
      vnode = createComponent(Ctor, data, context, children, tag)
    }
// 2. createComponent() 中調(diào)用創(chuàng)建自定義組件對應(yīng)的 VNode
export function createComponent (
  Ctor: Class<Component> | Function | Object | void,
  data: ?VNodeData,
  context: Component,
  children: ?Array<VNode>,
  tag?: string
): VNode | Array<VNode> | void {
  if (isUndef(Ctor)) {
    return
  }

  // ****

  // install component management hooks onto the placeholder node
  // 安裝組件的鉤子函數(shù) init/prepatch/insert/destroy
  // 準備好了 data.hook 中的鉤子函數(shù)
  installComponentHooks(data)

  // return a placeholder vnode
  const name = Ctor.options.name || tag
  // 創(chuàng)建自定義組件的 VNode,設(shè)置自定義組件的名字
  // 記錄this.componentOptions = componentOptions
  const vnode = new VNode(
    `vue-component-${Ctor.cid}${name ? `-${name}` : ''}`,
    data, undefined, undefined, undefined, context,
    { Ctor, propsData, listeners, tag, children },
    asyncFactory
  )

// ***

  return vnode
}
// 3. installComponentHooks() 初始化組件的 data.hook
function installComponentHooks (data: VNodeData) {
  const hooks = data.hook || (data.hook = {})
  // 用戶可以傳遞自定義鉤子函數(shù)
  // 把用戶傳入的自定義鉤子函數(shù)和 componentVNodeHooks 中預(yù)定義的鉤子函數(shù)合并
  for (let i = 0; i < hooksToMerge.length; i++) {
    const key = hooksToMerge[i]
    const existing = hooks[key]
    const toMerge = componentVNodeHooks[key]
    if (existing !== toMerge && !(existing && existing._merged)) {
      hooks[key] = existing ? mergeHook(toMerge, existing) : toMerge
    }
  }
}
// 4. 鉤子函數(shù)定義的位置(init()鉤子中創(chuàng)建組件的實例) 
// inline hooks to be invoked on component VNodes during patch
const componentVNodeHooks = {
  init (vnode: VNodeWithData, hydrating: boolean): ?boolean {
    if (
      vnode.componentInstance &&
      !vnode.componentInstance._isDestroyed &&
      vnode.data.keepAlive
    ) {
      // kept-alive components, treat as a patch
      const mountedNode: any = vnode // work around flow
      componentVNodeHooks.prepatch(mountedNode, mountedNode)
    } else {
      const child = vnode.componentInstance = createComponentInstanceForVnode(
        vnode,
        activeInstance
      )
      child.$mount(hydrating ? vnode.elm : undefined, hydrating)
    }
  },

  prepatch (oldVnode: MountedComponentVNode, vnode: MountedComponentVNode) {
        // ***
  },

  insert (vnode: MountedComponentVNode) {
        // ***
  },

  destroy (vnode: MountedComponentVNode) {
    // ***
  }
}
//5 .創(chuàng)建組件實例的位置,由自定義組件的 init() 鉤子方法調(diào)用
  function createComponentInstanceForVnode (
    vnode, // we know it's MountedComponentVNode but flow doesn't
    parent // activeInstance in lifecycle state
  ) {
    var options = {
      _isComponent: true,
      _parentVnode: vnode,
      parent: parent
    };
    // check inline-template render functions
    // 獲取 inline-template
    // <comp inline-template> xxxx </comp>
    var inlineTemplate = vnode.data.inlineTemplate;
    if (isDef(inlineTemplate)) {
      options.render = inlineTemplate.render;
      options.staticRenderFns = inlineTemplate.staticRenderFns;
    }
    // 創(chuàng)建組件實例
    return new vnode.componentOptions.Ctor(options)
  }

組件實例的創(chuàng)建和掛載過程

  • Vue._update() --> patch() --> createElm() --> createComponent()
// src\core\vdom\patch.js
// 1. 創(chuàng)建組件實例,掛載到真實 DOM
    function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
      var i = vnode.data;
      if (isDef(i)) {
        var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;
        if (isDef(i = i.hook) && isDef(i = i.init)) {
          // 調(diào)用 init() 方法,創(chuàng)建和掛載組件實例
          // init() 的過程中創(chuàng)建好了組件的真實 DOM,掛載到了 vnode.elm 上
          i(vnode, false /* hydrating */);
        }
        // after calling the init hook, if the vnode is a child component
        // it should've created a child instance and mounted it. the child
        // component also has set the placeholder vnode's elm.
        // in that case we can just return the element and be done.
        if (isDef(vnode.componentInstance)) {
          // 調(diào)用鉤子函數(shù)(VNode的鉤子函數(shù)初始化屬性/事件/樣式等,組件的鉤子函數(shù))
          initComponent(vnode, insertedVnodeQueue);
          // 把組件對應(yīng)的 DOM 插入到父元素中
          insert(parentElm, vnode.elm, refElm);
          if (isTrue(isReactivated)) {
            reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);
          }
          return true
        }
      }
    }
// 2. 調(diào)用鉤子函數(shù),設(shè)置局部作用于樣式
    function initComponent (vnode, insertedVnodeQueue) {
      if (isDef(vnode.data.pendingInsert)) {
        insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
        vnode.data.pendingInsert = null;
      }
      vnode.elm = vnode.componentInstance.$el;
      if (isPatchable(vnode)) {
        // 調(diào)用鉤子函數(shù)
        invokeCreateHooks(vnode, insertedVnodeQueue);
        // 設(shè)置局部作用于樣式
        setScope(vnode);
      } else {
        // empty component root.
        // skip all element-related modules except for ref (#3455)
        registerRef(vnode);
        // make sure to invoke the insert hook
        insertedVnodeQueue.push(vnode);
      }
    }
// 3. 調(diào)用鉤子函數(shù)
    function invokeCreateHooks (vnode, insertedVnodeQueue) {
      // 調(diào)用 VNode 的鉤子函數(shù)
      for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
        cbs.create[i$1](emptyNode, vnode);
      }
      i = vnode.data.hook; // Reuse variable
      // 調(diào)用組件的鉤子函數(shù)
      if (isDef(i)) {
        if (isDef(i.create)) { i.create(emptyNode, vnode); }
        if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); }
      }
    }

Demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容