vue 源码分析--大结局版本

336 阅读2分钟

一. vue 渲染页面后,会替换我们的参数 el: '#root'元素

image.png

image.png

二、渲染步骤

  1. 字符串模板 -> AST(抽象语法树)
  2. AST -> VNode(虚拟DOM)
  3. VNode -> DOM

三、 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./index.js"></script>
</head>
<body>
  <div id="root">
    <header>
      <h1>{{ title }}</h1>
    </header>
    <div>{{ msg }}-{{footer}}</div>
    <p>{{obj.name}}</p>
    <h1>{{arr}}</h1>
  </div>
  </div>

<script>
let data = {
  title: '标题',
  msg: '消息',
  footer: '结尾',
  obj: {
    name: '夏'
  },
  arr: [0,1]
}


let app = new Vue2({
  el: '#root',
  data
})

</script>
</body>
</html>

四、index.js

// 创建一个 得到虚拟DOM 的构造函数 => Vnode
class Vnode {
  constructor(tag, attrs, type, value) {
    this.tag = tag && tag.toLowerCase();          // 获取元素标签名
    this.attrs = attrs;                           // 获取元素节点中的属性
    this.type = type;                             // 获取节点类型
    this.value = value;                           // 获取文本节点的文本值
    this.children = [];                           // 元素节点子节点初始化为空
  }
  // 给元素节点增加子节点
  appendChild(vNode) {
    this.children.push(vNode)
  }
}


class Vue2 {
  constructor(opt) {
    this._el = opt.el;
    // 文档中匹配指定 CSS 选择器的一个元素
    this.$el = document.querySelector(opt.el);      
    this._data = opt.data;
    // 获取当前元素的父节点
    this._parentNode = this.$el.parentNode;        

    this.setReative(opt.data)
    this.mounted()
  }

  /**
 * 数据劫持
 * @param {*} target 
 * @param {*} key 
 * @param {*} value 
 */
  objectReative(target, key, value) {
    let dep;
    Object.defineProperty(target, key, {
      get: () => {
        if (value instanceof Object && !!value && typeof value !== 'function') {
          this.setReative(value)
        }
        // 这里需要实现多个 vue实例,共用一个属性,就是vuex的效果,还没想到怎么实现
        return value
      },
      set: (newval) => {
        value = newval
        this.mounted()
      }
    })
  }

  setReative(data) {
    Object.keys(data).forEach(key => {
      this.objectReative(data, key, data[key])
    })
  }

  /**
   * 根据'data.obj.name';去除name的值
   * @param {*} string 
   * @param {*} data 
   * @returns 
   */
  getDeepVal(string, data) {
    let arr = string.split('.')
    let val = data
    arr.forEach(item => {
      val = val[item]
    })
    return val
  }

  /**
   * 创建ast。我们这里简单用dom创建代替,实际vue使用字符串创建
   * @param {*} node 
   * @returns 
   */
  createAst(node) {
    let vNode = {};
    let type = node.nodeType
    if (type === 1) {
      let attrs = [...node.attributes]
      attrs = attrs.map(attr => ({
        name: attr.name,
        value: attr.nodeValue
      }))
      vNode = new Vnode(node.nodeName, attrs, 1, undefined)
      if (node.childNodes?.length) {
        node.childNodes.forEach(childNode => {
          vNode.appendChild(this.createAst(childNode))
        })
      }
    } else if (type === 3) {
      vNode = new Vnode(undefined, undefined, 3, node.nodeValue)
    }

    return vNode;
  }

  /**
   * 生成render方法,使用闭包,把ast缓存在函数里
   * @returns 
   */
  createRender() {
    // 字符串模板,解析成ast(抽象语法树),并且缓存起来
    let ast = this.createAst(this.$el)
    // 这里是render方法,创建(返回)虚拟dom
    return function render() {
      let vNode = this.compiler(ast)
      return vNode
    }
  }

  /**
   * 把ast结合data,编译成填充好数据的vNode
   * @param {*} vNode 
   * @returns 
   */
  compiler(vNode) {
    let newVNode = {}
    let type = vNode.type
    if (type === 1) {
      newVNode = new Vnode(vNode.tag, vNode.attrs, 1, undefined)
      if (vNode.children?.length) {
        vNode.children.forEach(childVNode => {
          newVNode.appendChild(this.compiler(childVNode))
        })
      }
    } else if (type === 3) {
      let value = vNode.value.replace(/{{(.+?)}}/g, (_, g) => {
        let key = g.trim()
        return this.getDeepVal(key, this._data)
      })
      newVNode = new Vnode(undefined, undefined, 3, value)
    }

    return newVNode
  }

  /**
   * 创建真实dom,vue这里可以进行diff算法对比
   * @param {} vNode 
   * @returns 
   */
  parseNode(vNode) {
    let node;
    let type = vNode.type
    if (type === 1) {
      node = document.createElement(vNode.tag)
      vNode.attrs.forEach(attr => {
        node.setAttribute(attr.name, attr.value)
      })
      if (vNode.children) {
        vNode.children.forEach(item => {
          node.appendChild(this.parseNode(item))
        })
      }
    } else if (type === 3) {
      node = document.createTextNode(vNode.value)
    }
    return node
  }

  /**
   * 更新视图
   * @param {} vNode 
   */
  update(vNode) {
    let realDom = this.parseNode(vNode)
    this._parentNode.replaceChild(realDom, document.querySelector(this._el))
  }

  /**
   * 挂载真实dom到el
   */
  mounted() {
    this.render = this.createRender()
    const mounted = () => {
      this.update(this.render())
    }
    mounted()
  }
}