Vue mount内部实现

98 阅读1分钟

根据render函数生成真实的dom

<div id="app"></div>

function h(tag, props, children) {
  return {
    tag,
    props,
    children,
  }
}
function mount(vnode, container) {
  //创建元素节点
  const el = document.createElement(vnode.tag)
  //props 属性
  if (vnode.props) {
    for (const key in vnode.props) {
      const value = vnode.props[key]
      el.setAttribute(key, value)
    }
  }
  //children 子元素
  if (vnode.children) {
    if (typeof vnode.children == 'string') {
      el.textContent = vnode.children
    } else {
      vnode.children.forEach((child) => {
        mount(child, el)
      })
    }
  }
  //完成挂载
  container.appendChild(el)
}
const vdom = h('div', { class: 'red' }, [h('div', null, 'hello')])
mount(vdom, document.getElementById('app'))