You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionmountElement(VNode,container){let{
tag,
data,
children
}=VNode;constel=createElement(tag);// document.createElement(tag)//处理DOM属性for(letkeyindata){data.hasOwnProperty(key)&&patchData(el,key,null,data[key]);}//处理子节点//多子节点if(children&&Array.isArray(children)){for(leti=0;i<children.length;i++){mount(children[i],el)}}//单节点elseif(children){mount(children,el)}appendChild(container,el);// container.appendChild(el)}//用于处理dom节点的属性,比如style class 事件等...functionpatchData(){//...}
The text was updated successfully, but these errors were encountered:
虚拟DOM之挂载
用 VNode 描述真实 DOM
虚拟DOM简而言之就是,用JS去按照DOM结构来实现的树形结构对象,一般称之为虚拟节点(VNode)
一个 html 标签有它的名字、属性、事件、样式、子节点等诸多信息,这些内容都需要在 VNode 中体现,我们可以用如下对象来描述一个红色背景的正方形 div 元素:
这个例子中,使用tag表示标签的名字,data用来存储附加信息
我们再考虑存在子节点的情况,使用children表示div元素的子节点:
当然,元素的子节点可能会有多个,那么我们将children变为数组来接收子节点:
除了html标签之外,再考虑文本节点:
现在我们知道如何用VNode来描述DOM结构了,但是如果开发中需要手写VNode,那绝对是反人类的,所以接下来,我们来介绍h函数。
h函数
h函数作为创建VNode对象的函数封装,React中通过babel将JSX转换为h函数的形式,Vue中通过vue-loader将模板转换为h函数。
假如在Vue中我们有如下模板:
用 h 函数来创建与之相符的 VNode:
得到的 VNode 对象如下:
假如在Vue中我们有如下模板:
用 h 函数来创建与之相符的 VNode:
得到的 VNode 对象如下:
实现 h 函数:
挂载
所谓挂载就是将VNode转换为真实DOM的过程,通常称之为render。
render函数分为两部分:
今天主要来理解mount部分
我们封装mountElement函数用于挂载标签,mountText函数用于挂载文本节点。
先看mountText函数:
再看mountElement函数:
The text was updated successfully, but these errors were encountered: