在学习vue入门时,一直有一个疑惑如何把虚拟dom转换成真实dom的。
现在猜想,假设虚拟dom长这样,表示要渲染的内容。
const testObj = {tag: 'div',children: [{tag: 'h1', children: '标题'},{tag: 'h1', children: '标题'},{tag: 'h1', children: '标题'},{tag: 'div', children: [{tag: 'h1', children: '虚拟dom'},]},]}
tag和children是必要属性,tag表示标签名,children表示该标签的子属性。
通过两年半的学习发现是需要创建dom的,然后将创建的dom挂在根dom上就完成渲染了。
const render = (customDom, root) => {const el = document.createElement(customDom.tag);if (typeof customDom.children === 'string') {el.innerHTML = customDom.children;} else if (typeof customDom.children === 'object') {Object.values(customDom.children).forEach((item) => render(item, el))}root.appendChild(el)}
使用时将需要渲染的对象和根dom传进去就能完成渲染
render(testObj, document.body)