Vue函數(shù)式組件專篇深入分析
函數(shù)式組件的實現(xiàn)相對容易。一個函數(shù)式組件本質(zhì)上就是一個普通函數(shù),該函數(shù)的返回值是虛擬DOM。
在用戶接口層面,一個函數(shù)式組件就是一個返回虛擬DOM的函數(shù),如下面的代碼所示:
function MyFuncComp(props){ return {type:'h1',children: porps.title} }
函數(shù)式組件沒有自身狀態(tài),但仍然可以接收由外部傳入的props。為了給函數(shù)式組件定義props,需要在組件函數(shù)上添加靜態(tài)的props屬性,如下面代碼所示:
function MyFuncComp(props){ return {type:'h1',children:props.title} } // 定義props MyFuncComp.props = { title: String }
在有狀態(tài)組件的基礎(chǔ)上,實現(xiàn)函數(shù)式組件將變得非常簡單,因為掛載組件的邏輯可以復用mountComponent函數(shù),為此,需要在patch函數(shù)內(nèi)支持函數(shù)類型的vnode.type,如下面patch函數(shù)的代碼所示:
function patch(n1,n2,container, anchor){ if(n1 && n1.type !== n2.type){ unmount(n1) n1 = null } const {type} = n2 if(typeof type === 'string'){ // 省略部分代碼 }else if(type === Text) { // 省略部分代碼 }else if(type === Fragment) { // 省略部分代碼 }else if(type === 'object' || typeof type === 'function') { // component if(!n1){ mountComponent(n2,container,anchor) }else{ patchComponent(n1,n2,anchor) } } }
在patch函數(shù)內(nèi)部,通過檢測vnode.type的類型來判斷組件的類型
- 如果vnode.type是一個對象,則它是一個有狀態(tài)組件,并且vnode.type是組件選項對象;
- 如果vnode.type是一個函數(shù),則它是一個函數(shù)式組件
下面是修改后的mountComponent函數(shù),其支持掛載函數(shù)式組件:
function mountComponent(vnode,container,anchor){ // 檢查是否是函數(shù)式組件 const isFunctional = typeof vnode.type === 'function' let componentOptions = vnode.type if(isFunctional){ // 如果是函數(shù)式組件,則將vnode.type作為渲染函數(shù),將vnode.type.props作為props選項定義即可 componentOptions = { render:vnode.type, props: vnode.type.props } } // 省略部分代碼 }
實現(xiàn)對函數(shù)式組件的兼容非常簡單。首先,在mountComponent函數(shù)內(nèi)檢查組件的類型,如果是函數(shù)式組件,則直接將組件函數(shù)作為組件選項對象的render選項,并將組件函數(shù)的靜態(tài)props屬性作為組件的props選項即可。
當然,出于更加嚴謹?shù)目紤],我們需要通過isFunctional變量實現(xiàn)選擇性地執(zhí)行初始化邏輯,
到此這篇關(guān)于Vue函數(shù)式組件專篇深入分析的文章就介紹到這了,更多相關(guān)Vue函數(shù)式組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
TypeError:res.forEach?is?not?a?function報錯解決辦法
這篇文章主要給大家介紹了關(guān)于TypeError:res.forEach?is?not?a?function報錯的解決辦法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2023-07-07vue+render+jsx實現(xiàn)可編輯動態(tài)多級表頭table的實例代碼
這篇文章主要介紹了vue+render+jsx實現(xiàn)可編輯動態(tài)多級表頭table的實例代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的工作或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04