美文网首页
vue源码分析复习

vue源码分析复习

作者: 三省吾身_9862 | 来源:发表于2022-04-14 17:31 被阅读0次

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

image.png 原来html中的root被替换了

渲染步骤

  1. 字符串模板 -> AST
  2. AST -> VNode
  3. VNode -> DOM
index.js
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;
    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()
  }
}
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>
  <hr>
  <div id="root2">
    <header>
      <h1>{{ msg }}</h1>
    </header>
  </div>

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


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

let app2 = new Vue2({
  el: '#root2',
  data: {
    msg: 'xx'
  }
})
</script>
</body>
</html>

相关文章

网友评论

      本文标题:vue源码分析复习

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