閱讀vue原始碼後,簡單實現虛擬dom

尼古拉斯二嘎發表於2020-12-20

class Element {
  constructor (type, props, children) {
    this.type = type
    this.props = props
    this.children = children
  }
}

const ul = createElement(
  'ul', 
  {id: 'list'}, 
  [
    createElement('li', {class: 'item'}, ['Item 1']),
    createElement('li', {class: 'item'}, ['Item 2']),
    createElement('li', {class: 'item'}, ['Item 3'])
  ]
)

function createElement (type, props, children) {
  return new Element(type, props, children)
}

function createNode (node) {
  let el = document.createElement(node.type)
  for (let key in node.props) {
    if (node.type.toUpperCase() === 'INPUT' || node.type.toUpperCase() === 'TEXTAREA') {
      el.value = node.props[key]
    } else {
      el.setAttribute(key, node.props[key])
    }
  }
  return el
}

ul.render = function (node = ul) {
  let root = createNode(node)
  if (node.children && node.children.length > 0) {
    node.children.forEach(ele => {
      if (ele instanceof Element) {
        root.appendChild(ul.render(ele))
      } else {
        root.appendChild(document.createTextNode(ele))
      }
    })
  }
  return root
}


const ulRoot = ul.render()
document.body.appendChild(ulRoot)

相關文章