关于前端:微型Vue框架构建Part3Mount方法实现

6次阅读

共计 1793 个字符,预计需要花费 5 分钟才能阅读完成。

  • 如何给 Vue 对象的原型链增加 $Mount 办法initMout
  • 为实在节点生成虚构 DOM,具体实现办法contrucVNode
  • 定义虚构 Node 节点类, VNode
  • $Mount 办法实现概览

相干链接

  • PS:node 节点的属性和办法
  • PS:nodeType 的值有哪些,代表什么意思

如何给 Vue 对象的原型链增加 $Mount 办法

  • initMout 办法导出,传入 Vue 对象

      /**
       * 在原型链上增加 #mount 办法
       * @param {*} Vue
       */
      export function initMout(Vue) {Vue.prototype.$mount = function (el) {
          const vm = this;
          this._el = el;
          mount(vm, el);
        };
      }
    

    将实在节点生成虚构 DOM

  • 每个实在 DOM 节点都会继承 Node 类,所以通过 nodeName 能晓得是 HTML 标签类型还是文本类型。(PS:node 类的属性和办法)
  • nodeType的值代表不同的含意,典型有 1 示意 HTML 标签,3 示意文本标签(PS:nodeType 的值有哪些,代表什么意思)
  • nodeName 是怎么定义文本类型的:两个节点间的空白局部和理论的文字都是文本类型

    1. <div id="app"> 标签后开始到“文本内容”这个文字前是一个文本类型#text
    2. “ 文本类容 ” 文字到 <span>标签前 是一个文本类型#text
    3. <span class="a">{{content}}</span>是个 SPAN 类型

```js
     <div id="app"> 
       文本内容:<span class="a">{{content}}</span> 
    </div>
```
  • children 属性就是下面代码块生成的虚构 DOM
  • 代码实现

    /**
     *  构建虚构 DOM
     * @param {*} vm
     * @param {*} el 实在的 DOM 节点
     * @param {*} parent 父级节点
     */
    function contrucVNode(vm, el, parent) {
      const tag = el.nodeName;
      const children = []; // 虚构 DOM 下的虚构子节点
      const text = getTextContent(el);
      const data = "";
      const nodeType = el.nodeType;

      const vnode = new VNode(tag, el, children, text, data, parent, nodeType);

      // 实在 DOM 节点下是否还有子节点
      const childrenList = el.childNodes;

      for (let i = 0; i < childrenList.length; i++) {const childrenNode = contrucVNode(vm, childrenList[i], parent);
        if (childrenNode instanceof VNode) {vnode.children.push(childrenNode);
        }
      }

      return vnode;
    }

定义虚构 Node 节点类

    export default class Vnode {
      // node 节点的内置属性和办法:https://developer.mozilla.org/en-US/docs/Web/API/Node
      // nodeType 的值:https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
      constructor(
        tag, // 标签类型,DIV、SPAN... #TEXT
        elm, // 对应实在节点, 前期会依据这个属性操作实在 DOM,如数据渲染
        children, // 以后节点下的虚构子节点(虚构 DOM)
        text, // 以后节点中文本内容
        data, // VNodeData, 临时保留,暂无意义
        parent, // 父级节点
        nodeType // 节点类型
      ) {
        this.tag = tag;
        this.elm = elm;
        this.children = children;
        this.text = text;
        this.data = data;
        this.parent = parent;
        this.nodeType = nodeType;

        this.env = {}; // 以后节点的环境变量
        this.instructions = null; // 寄存 Due 指令,如 v -for
        this.template = []; // 以后节点波及到的模板语法——形如{{ text}}
      }
    }

正文完
 0