1. FunctionalRenderContext
创建函数式组件的上下文:
ts
export function FunctionalRenderContext(
data: VNodeData,
props: Object,
children: Array<VNode> | undefined,
parent: Component,
Ctor: typeof Component
) {
// ... 前置代码 ...
// 核心属性初始化
this.data = data
this.props = props
this.children = children
this.parent = parent
this.listeners = data.on || emptyObject
this.injections = resolveInject(options.inject, parent)
// slots 相关逻辑
this.slots = () => {
if (!this.$slots) {
normalizeScopedSlots(/*...*/)
}
return this.$slots
}
// ... 其他配置 ...
}
2. createFunctionalComponent
创建函数式组件的主入口:
ts
export function createFunctionalComponent(
Ctor: typeof Component,
propsData: Object | undefined,
data: VNodeData,
contextVm: Component,
children?: Array<VNode>
): VNode | Array<VNode> | void {
// 1. 处理 props
const props = {}
// ... props 处理逻辑 ...
// 2. 创建渲染上下文
const renderContext = new FunctionalRenderContext(/*...*/)
// 3. 执行渲染
const vnode = options.render.call(null, renderContext._c, renderContext)
// 4. 处理渲染结果
if (vnode instanceof VNode) {
return cloneAndMarkFunctionalResult(/*...*/)
} else if (isArray(vnode)) {
// 处理数组类型的结果
// ...
}
}
3. cloneAndMarkFunctionalResult
克隆并标记函数式组件结果:
ts
function cloneAndMarkFunctionalResult(vnode, data, contextVm, options, renderContext) {
const clone = cloneVNode(vnode)
clone.fnContext = contextVm
clone.fnOptions = options
// ... 其他标记逻辑 ...
return clone
}