Vue3系列 - 渲染函数与JSX支持
Vue3中的渲染函数主要通过h函数实现,它是createElement的别名,源码位于src/v3/h.ts。
export function h(type: any, props?: any, children?: any) {
if (!currentInstance) {
__DEV__ &&
warn(
`globally imported h() can only be invoked when there is an active ` +
`component instance, e.g. synchronously in a component's render or setup function.`
)
}
return createElement(currentInstance!, type, props, children, 2, true)
}渲染函数的核心特点:
组件上下文检查:
h函数会检查当前是否有活跃的组件实例。参数灵活性:支持多种参数形式,可以传入标签名、组件选项或组件构造函数。
JSX转换:Vue的JSX会被编译为
h函数调用,使得开发者可以使用类似React的语法。内部实现:最终调用的是Vue核心的
createElement函数,它负责创建虚拟DOM节点。
渲染函数提供了比模板更灵活的方式来构建UI,特别适合那些需要基于动态数据结构渲染的场景。