模拟一下函数式组件过程,这样不用看Vue源码,也能理解这一过程。
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<div id="app">
</div>
<script>
function VNode(tagName, data){ //虚拟node节点构造函数
this.tagName = tagName;
this.data = data;
}
function createEle(tag, data){ //创建虚拟node
var vnode = new VNode(tag, data);
return vnode;
}
function render(createEle_, context){ //render函数
return createEle_("div", {
width : context.width,
height : context.height,
backgroundColor : context.backgroundColor
});
}
function patch(vnode_){ //创建真实节点
var myDiv = document.createElement(vnode_.tagName);
myDiv.style.width = vnode_.data.width;
myDiv.style.height = vnode_.data.height;
myDiv.style.backgroundColor = vnode_.data.backgroundColor;
document.getElementById("app").appendChild(myDiv);
}
var context = {
width : "200px",
height : "200px",
backgroundColor : "red"
}
var vnode = render.call(null, createEle, context);
patch(vnode);
</script>
</body>
</html>
成功渲染出了200X200的红色方块。