函数式组件

2025/3/11 Vue3组件

在 vue2 中,相比有状态组件,函数组件具有明显的性能优势,但是在 vue 3 中,两者差距不大即使是有状态组件,它的初始化消耗也非常低。使用它主要是因为它的简单性。

函数组件本质上是一个普通函数,该函数的返回值是一个虚拟 DOM 对象。

实现它只需要在 patch 函数中支持函数类型的 vnode.type 即可

function patch(n1, n2, container, anchor) {
  // ...
  const { type } = n2
  if (typeof type === 'string') {
   // ... 
  }else if(typeof type === 'function' || typeof type === 'object'){
    // type 是对象 说明是有状态组件 并且 vnode.type 是组件选项的对象
    // type 是函数 说明是函数式组件 
    if(!n1){
      mountComponent(n2, container, anchor)
    }else{
      parentComponent(n1, n2, anchor)
    }
  }
}

function mountComponent(vnode, container, anchor) {
  // 是否是函数组件
  const isFunctional =  typeof vnode.type === 'function'
  
  let componentOptions = vnode.type
  
  if(isFunctional){
    // 如果是函数组件则直接将 vnode.type 作为渲染函数
    componentOptions = {
      render: vnode.type,
      props: vnode.type.props,
    }
  }
  // ...
}
Last Updated: 2026/06/09/ 06:29:26