Vue源码学习之createElement

本文深入探讨Vue源码中的createElement方法,详细解释了如何创建虚拟节点(VNode),包括VNode的结构、createElement的内部逻辑,以及children的标准化过程。通过对不同场景的分析,展示了Vue如何构建VNode树,为真实DOM的渲染做准备。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue源码学习之createElement

在Vue应用开发中,我们大部分时间都是使用template来创建HTML,但是在一些场景中,我们可能会需要在js进行模板的编写及渲染,这时候我们就会用到Vue中的渲染函数render,像下面这样:

Vue.component('renderTest', {
   
  render: function (createElement) {
   
    return createdElement('h1', 'this is test render')
  }
})

可以看到在render函数里面我们主要用到了createElement来进行模板的创建,那createElement里面到底进行了什么操作来进行temlate的创建的呢?

VNode

首先我们要知道createElement返回的其实不是一个真实的DOM元素,而是一个js对象,我们把这样的对象称为“虚拟节点(Virtual Node)”,VNode是对真实DOM的一种抽象描述,它包含了真实DOM节点所对应的各种属性,标签名、数据、子节点、键值等。VNode在src/core/vdom/vnode.js中定义

export default class VNode {
   
  tag: string | void;
  data: VNodeData | void;
  children: ?Array<VNode>;
  text: string | void;
  elm: Node | void;
  ns: string | void;
  context: Component | void; // rendered in this component's scope
  key: string | number | void;
  componentOptions: VNodeComponentOptions | void;
  componentInstance: Component | void; // component instance
  parent: VNode | void; // component placeholder node

  // strictly internal
  raw: boolean; // contains raw HTML? (server only)
  isStatic: boolean; // hoisted static node
  isRootInsert: boolean; // necessary for enter transition check
  isComment: boolean; // empty comment placeholder?
  isCloned: boolean; // is a cloned node?
  isOnce: boolean; // is a v-once node?
  asyncFactory: Function | void; // async component factory function
  asyncMeta: Object | void;
  isAsyncPlaceholder: boolean;
  ssrContext: Object | void;
  fnContext: Component | void; // real context vm for functional nodes
  fnOptions: ?ComponentOptions; // for SSR caching
  fnScopeId: ?string; // functional scope id support

  constructor (
    tag?: string,
    data?: VNodeData,
    children?: ?Array<VNode>,
    text?: string,
    elm?: Node,
    context?: Component,
    componentOptions?: VNodeComponentOptions,
    asyncFactory?: Function
  ) {
   
    this.tag = tag
    this.data = data
    this.children = children
    this.text = text
    this.elm = elm
    this.ns = undefined
    this.context = context
    this.fnContext = undefined
    this.fnOptions = undefined
    this.fnScopeId = undefined
    this.key = data && data.key
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值