美文网首页
vertualDom --虚拟dom

vertualDom --虚拟dom

作者: 田成力 | 来源:发表于2019-12-11 10:49 被阅读0次
    
    class Element {
      constructor(type, props, children) {
        this.type = type;
        this.props = props;
        this.children = children;
      }
    }
    //设置属性
    function setAttr(node, key, value) {
      switch (key) {
        case 'value':
          if (node.tagName.toUpperCase() === 'INPUT' || node.tagName.toUpperCase() === 'TEXTAREA') {
            node.value = value;
          } else {
            node.setAttribute(key, value);
          }
          break;
        case 'style':
          node.style.cssText = value;
          break;
        default:
          node.setAttribute(key, value);
          break;
      }
    }
    //返回虚拟节点
    function createElement(type, props, children) {
      return new Element(type, props, children);
    }
    //将虚拟dom转换为真实dom
    function render(eleObj) {
      let el = document.createElement(eleObj.type);
      for (let key in eleObj.props) {
        setAttr(el, key, eleObj.props[key]);
      }
      //遍历儿子节点,如果屎虚拟dom继续渲染,不是的话就是文本节点
      eleObj.children.forEach((children) => {
        child = (child instanceof Element) ? render(child) : document.createTextNode(child);
        el.appendChild(child);
      })
      return el;
    }
    //将元素插入到页面中
    function renderDom(el, target) {
      target.appendChild(el)
    }
    
    
    let vertualDom = createElement('ul', { class: 'list' }, [
      createElement('li', { class: 'item' }, ['a']),
      createElement('li', { class: 'item' }, ['b']),
      createElement('li', { class: 'item' }, ['c']),
    ]);
    let el = render(vertualDom);
    renderDom(el, window.root);
    console.log(vertualDom);
    
    

    相关文章

      网友评论

          本文标题:vertualDom --虚拟dom

          本文链接:https://www.haomeiwen.com/subject/wehogctx.html