Render函数简单实现

2/2/2023 vue

“ Talk is cheap, show me the code”

// ast语法树
let ast = {
	tag: 'div',
	attr: {
		class: 'banner',
		id: 'banner',
	},
	text: '商品Banner',
	children: [
		{
			tag: 'div',
			attr: {
				class: 'bannerItem',
				key: '101',
			},
			text: '图片1',
			children: [
				{
					tag: 'img',
					attr: {
						class: 'bannerCover',
						src: 'https://www.baidu.com/imgs/1.png',
					},
				},
			],
		},
		{
			tag: 'div',
			attr: {
				class: 'bannerItem',
				key: '102',
			},
			text: '图片2',
			children: [
				{
					tag: 'img',
					attr: {
						class: 'bannerCover',
						src: 'https://www.baidu.com/imgs/1.png',
					},
				},
			],
		},
	],
}

function render(root, ast) {
	let { tag, attr, text, children } = ast
	let ele = document.createElement(tag)
	for (let key in attr) ele.setAttribute(key, attr[key])
	ele.innerText = text
	children && children.forEach((item) => render(ele, item))
	root.appendChild(ele)
}

let root = document.getElementById('app')
render(root, ast)

Loading comments...

    我想,
    在这个世界上,
    虽然没有最美好的相遇,
    但却应该有为了相遇或重逢,
    所做的最美好的努力。
    SKIP >
    红莲华
    x
    天上飘着些微云,地上吹着些微风。啊!微风吹动了我头发,教我如何不想她?