
封装的目的是可重复调用,也支持父子元素嵌套,封装函数如下:
import { h } from "vue";
//动态生成DOM元素,参数 @param {Object} nodeConfig 节点配置 { tag, props, children }
createElement: (nodeConfig) => {
// 递归生成虚拟节点
const generateVNode = (config) => {
const { tag, props = {}, children = [] } = config;
// 子节点递归处理:数组项为配置对象时递归,否则直接作为文本/元素
const childVNodes = children.map(child => {
return typeof child === 'object' && child.tag ? generateVNode(child) : child;
});
return h(tag, props, childVNodes);
};
const vnode = generateVNode(nodeConfig);
return vnode;
}
调用并挂载代码如下:
/**
*<div id="content"></div>
*/
import { render } from 'vue'
const vnode = createElement({
tag: 'div', props: {}, children: [
{ tag: 'h2', props: { style: 'color:#EE0000' }, children: ['这是标题'] },
{ tag: 'p', props: { class: 'con' }, children: ['这是内容!',{ tag: 'span', props: { class: 'gray' }, children:['这是标签']}] }
]
});
render(vnode, document.querySelector('#content'));
卸载方法:
const unmount = () => {
render(null, document.querySelector('#content'));
};
上一篇:Naive UI日期选择器转为中文,选中时间戳转为日期格式yyy-MM-DD
下一篇:没有了
讨论数量:0