Vue源碼閱讀之5渲染初始化

前面的章節講述了從創建到BeforeCreated的前兩個過程生命週期初始化和事件的初始化,這裏講述這裏的最後一個過程渲染初始化,渲染初始化完成之後便完成了BeforeCreated。

export function initRender (vm: Component) {
  vm._vnode = null
  const options = vm.$options
  const parentVnode = vm.$vnode = options._parentVnode 
  const renderContext = parentVnode && parentVnode.context
  vm.$slots = resolveSlots(options._renderChildren, renderContext)
  vm.$scopedSlots = emptyObject
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
  const parentData = parentVnode && parentVnode.data
  if (process.env.NODE_ENV !== 'production') {
    defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, () => {
      !isUpdatingChildComponent && warn(`$attrs is readonly.`, vm)
    }, true)
    defineReactive(vm, '$listeners', options._parentListeners || emptyObject, () => {
      !isUpdatingChildComponent && warn(`$listeners is readonly.`, vm)
    }, true)
  } else {
    defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true)
    defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true)
  }
}

首先初始化虛擬節點爲null。

定義變量options存儲Vue對象$options屬性。

定義變量parentVnode同時設置Vue對象的值爲options._parentVnode即獲取父級的虛擬節點。

定義變量renderContext存儲父級虛擬節點的渲染內容。

設置Vue對象的$slots屬性用於處理此對象中的具名插槽和你們插槽。

設置Vue對象的$scopedSlots屬性用於處理此對象中的範圍插槽。

設置Vue對象的_c屬性其值爲createElement函數。

設置Vue對象的$createElement屬性其值爲createElement函數。

最後給Vue對象的$attrs和$listeners添加setter和getter函數,以及對屬性和事件的相關的監聽處理,這一部分內容比較多將會在後面的章節進行講解。

至此完成了從創建Vue對象到BeforeCreated的所有過程。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章