Vue(v2.6.14)源码解毒(预):手写一个简易版Vue

704 阅读4分钟

MVVM 设计模式,是由 MVC、MVP 等设计模式进化而来,M - 数据模型(Model),VM - 视图模型(ViewModel),V - 视图层(View)。MVVM 的核心是 ViewModel 层,它就像是一个中转站(value converter),负责转换 Model 中的数据对象来让数据变得更容易管理和使用,该层向上与视图层进行双向数据绑定,向下与 Model 层通过接口请求进行数据交互,起呈上启下作用。如下图所示:

MVVM

Vue中的MVVM思想

使用 MVVM 设计模式的前端框架很多,其中渐进式框架 Vue 是典型的代表,深得广大前端开发者的青睐。

mvvm

从上图中可以看出MVVM主要分为这么几个部分:

  • 模板编译(Compile)
  • 数据劫持(Observer)
  • 订阅-发布(Dep)
  • 观察者(Watcher)

我们来看一个 vue 的实例:

<!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>vue</title>
</head>
<body>
  <div id="app">
    <p>{{ number }}</p>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const VM = new Vue({
      el'#app',
      data: {
        number0
      },
    })
    setInterval(() => {
      VM.number++
    }, 1000)
  </script>
</body>
</html>

我们对原理进行分析一下:

  • 首先 new Vue() 执行初始化,通过 Observerdata 上的属性执行响应式处理。也就是 Object.defineProperty 对数据属性进行劫持。
  • 通过Compile 进行模板编译,对模板里动态绑定的数据,使用 data 数据进行初始化。
  • 在模板初始化时,在触发Object.defineProperty 内的 getter 时,创建更新函数和 Watcher 类。
  • 同一属性在模板中可能出现多次,就会创建多个Watcher ,就需要Dep 来统一管理。
  • 当数据发生变化时,找到属性对应的 dep ,通知所有 Watcher 执行更新函数。

创建Vue类

// 创建 Vue 类
class Vue {
  constructor(options) {
    // 保存选项
    this.$options = options;
    this.$data = options.data;
    // 响应式处理
    observe(this.$data)
    // 将数据代理到实例上
    proxyData(this'$data')
    // 用数据和元素进行编译
    new Compiler(options.elthis)
  }
}
// 代理数据的方法
function proxyData (vm, sourceKey) {
  Object.keys(vm[sourceKey]).forEach(key => {
    Object.defineProperty(vm, key, {
      get () {
        return vm[sourceKey][key]
      },
      set (newVal) {
        vm[sourceKey][key] = newVal
      }
    })
  })
}

上面代码创建了一个 Vue 类和 proxyData 方法,Vue 类接收 options 参数,内部调用 observe 方法对传入参数 options.data 数据,递归进行响应式处理。 使用 proxyData 方法把数据代理到实例上,让我们获取和修改数据的时候可以直接通过 thisthis.$data, 如: this.numberthis.$data.number 。 最后使用 Compiler 对模板进行编译,初始化动态绑定的数据。

模板编译(Compile)

// 模板编译
class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    if (this.$el) {
      // 执行编译
      this.compile(this.$el)
    }
  }
  compile (el) {
    // 遍历 el 树
    const childNodes = el.childNodes;
    Array.from(childNodes).forEach((node) => {
      if (this.isElementNode(node)) { // 元素节点
        // 编译元素节点的方法
        this.compileElement(node)
      } else { // 文本节点
        // 编译文本节点的方法
        this.compileText(node)
      }
      // 如果还有子节点,继续递归
      if (node.childNodes && node.childNodes.length > 0) {
        this.compile(node);
      }
    })
  }
  // 判断是否是元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
  // 判断属性是否为指令
  isDirective (attr) {
    return attr.indexOf('v-') === 0
  }
  // 编译元素
  compileElement (node) {
    // 遍历节点属性
    const nodeAttrs = node.attributes
    Array.from(nodeAttrs).forEach((attr) => {
      const attrName = attr.name // 属性名
      const exp = attr.value // 动态判定的变量名
      //找到 v-xxx 的指令,如 v-text/v-html
      if (this.isDirective(attrName)) {
        let [, dir] = attrName.split("-"// 指令名 如 text/html
        // 调用指令对应得方法
        this[dir] && this[dir](node, exp)
      }
    })
  }
  // 编译文本
  compileText (node) {
    let txt = node.textContent// 获取文本节点的内容
    let reg = /\{\{(.*)\}\}/// 创建匹配 {{}} 的正则表达式
    // 如果存在 {{}} 则使用 text 指令的方法
    if (node.nodeType === 3 && reg.test(txt)) {
      this.update(node, RegExp.$1.trim(), 'text')
    }
  }
  update (node, exp, dir) {
    // 调用指令对应的更新函数
    const callback = this[dir + 'Updater'];
    callback && callback(node, this.$vm[exp])
    // 更新处理,创建 Watcher,保存更新函数
    new Watcher(this.$vm, exp, function (val) {
      callback && callback(node, val)
    })
  }
  // v-text
  text (node, exp) {
    this.update(node, exp, 'text')
  }
  textUpdater (node, value) {
    node.textContent = value
  }
  // v-html
  html (node, exp) {
    this.update(node, exp, 'html')
  }
  htmlUpdater (node, value) {
    node.innerHTML = value
  }
}

编译过程中,以根元素开始,也就是实例化 Vue 时传入的 options.el 进行递归编译节点,使用 isElementNode 方法判断是文本节点还是元素节点。 如果是文本节点,正则匹配(双大括号){{ xxx }};使用 v-text 指令方式初始化读取数据。 若为元素节点,遍历属性,找到 v-textv-html,初始化动态绑定的数据。 在初始化数据时,创建 Watcher 和更新函数。

数据劫持(Observer)

function observe (obj) {
  if (typeof obj !== 'object' || obj == null) {
    return;
  }
  // 传入境来的对象做响应式处理
  new Observer(obj)
}
function defineReactive (obj, key, val) {
  // 递归劫持数据
  observe(val)
  // 创建与 key 对应的 Dep 管理相关的 Watcher
  const dep = new Dep();
  //对数据进行劫持
  Object.defineProperty(obj, key, {
    get () {
      // 依赖收集
      Dep.target && dep.addDep(Dep.target)
      return val;
    },
    set (newVal) {
      if (newVal !== val) {
        // 如果 newVal 为 Object ,就需要对其响应式处理
        observe(newVal)
        val = newVal;
        // 通知更新
        dep.notify()
      }
    }
  })
}
class Observer {
  constructor(value) {
    this.value = value;
    if (typeof value === 'object') {
      this.walk(value)
    }
  }
  // 对象数据响应化
  walk (obj) {
    Object.keys(obj).forEach(key => {
      defineReactive(obj, key, obj[key])
    })
  }
}

上面代码,创建了 observedefineReactive 方法,还有 Observer 类 。 observe 方法用于类型判断。 Observer 类收一个参数,若参数是 object 类型,调用 defineReactive 方法对其属性进行劫持。 在 defineReactive 方法中,通过 Object.defineProperty 对属性进行劫持。并对每个 key 创建 Dep 的实例,还记得模板编译时,对动态绑定的值,进行初始化的时候会创建 Watcher 吗?Watcher 内保存有对应的更新函数;defineReactive 中,数据被读取的时候,就会触发 getter , getter 中就会把 Watcher push 到对应的 Dep 中,这个过程就叫做依赖收集。当值发生改变的时候,触发 setter 调用这个key 所对应的 Dep 内的 notify 方法,通知更新。

订阅-发布(Dep)

class Dep {
  constructor() {
    this.deps = []
  }
  addDep (dep) {
    this.deps.push(dep)
  }
  notify () {
    this.deps.forEach(dep => dep.update())
  }
}

每个 key 都会创建一个 Dep ,每个 Dep 内都会有一个 deps 数组,用来同一管理这个 key 所对应的 Watcher 实例。 addDep 方法用于添加订阅。 notify 方法用于通知更新。

观察者(Watcher)

// 观察者,保存更新函数。
class Watcher {
  constructor(vm, key, updateFn) {
    this.vm = vm
    this.key = key
    this.updateFn = updateFn
    Dep.target = this // 在静态属性上保存当前实例
    this.vm[this.key// 触发数据劫持 get
    Dep.target = null // 在读取属性 触发get后,依赖收集完毕,现在置空
  }
  update () {
    this.updateFn.call(this.vmthis.vm[this.key])
  }
}

Watcher 类接收三个参数,Vue 的实例、 绑定的变量名 keyupdateFn 更新方法。Watcher 在模板编译时被创建。我们用 Dep.target 静态属性来保存当前的实例。主动触发一次响应式的 getter , 使其实例被添加到 Dep 中,完成依赖收集,完成后,将静态属性 Dep.target 置空。 内部创建一个 update 更新方法。在 Depnotify 方法通知更新时被调用。

完整代码

// 模板编译
class Compiler {
  constructor(el, vm) {
    this.$vm = vm;
    this.$el = document.querySelector(el);
    if (this.$el) {
      // 执行编译
      this.compile(this.$el)
    }
  }
  compile (el) {
    // 遍历 el 树
    const childNodes = el.childNodes;
    Array.from(childNodes).forEach((node) => {
      if (this.isElementNode(node)) { // 元素节点
        // 编译元素节点的方法
        this.compileElement(node)
      } else { // 文本节点
        // 编译文本节点的方法
        this.compileText(node)
      }
      // 如果还有子节点,继续递归
      if (node.childNodes && node.childNodes.length > 0) {
        this.compile(node);
      }
    })
  }
  // 判断是否是元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
  // 判断属性是否为指令
  isDirective (attr) {
    return attr.indexOf('v-') === 0
  }
  // 编译元素
  compileElement (node) {
    // 遍历节点属性
    const nodeAttrs = node.attributes
    Array.from(nodeAttrs).forEach((attr) => {
      const attrName = attr.name // 属性名
      const exp = attr.value // 动态判定的变量名
      //找到 v-xxx 的指令,如 v-text/v-html
      if (this.isDirective(attrName)) {
        let [, dir] = attrName.split("-"// 指令名 如 text/html
        // 调用指令对应得方法
        this[dir] && this[dir](node, exp)
      }
    })
  }
  // 编译文本
  compileText (node) {
    let txt = node.textContent// 获取文本节点的内容
    let reg = /\{\{(.*)\}\}/// 创建匹配 {{}} 的正则表达式
    // 如果存在 {{}} 则使用 text 指令的方法
    if (node.nodeType === 3 && reg.test(txt)) {
      this.update(node, RegExp.$1.trim(), 'text')
    }
  }
  update (node, exp, dir) {
    // 调用指令对应的更新函数
    const callback = this[dir + 'Updater'];
    callback && callback(node, this.$vm[exp])
    // 更新处理,创建 Watcher,保存更新函数
    new Watcher(this.$vm, exp, function (val) {
      callback && callback(node, val)
    })
  }
  // v-text
  text (node, exp) {
    this.update(node, exp, 'text')
  }
  textUpdater (node, value) {
    node.textContent = value
  }
  // v-html
  html (node, exp) {
    this.update(node, exp, 'html')
  }
  htmlUpdater (node, value) {
    node.innerHTML = value
  }
}
// 创建 Vue 类
class Vue {
  constructor(options) {
    // 保存选项
    this.$options = options;
    this.$data = options.data;
    // 响应式处理
    observe(this.$data)
    // 将数据代理到实例上
    proxyData(this'$data')
    // 用数据和元素进行编译
    new Compiler(options.elthis)
  }
}
// 代理数据的方法
function proxyData (vm, sourceKey) {
  Object.keys(vm[sourceKey]).forEach(key => {
    Object.defineProperty(vm, key, {
      get () {
        return vm[sourceKey][key]
      },
      set (newVal) {
        vm[sourceKey][key] = newVal
      }
    })
  })
}
function observe (obj) {
  if (typeof obj !== 'object' || obj == null) {
    return;
  }
  // 传入境来的对象做响应式处理
  new Observer(obj)
}
function defineReactive (obj, key, val) {
  // 递归劫持数据
  observe(val)
  // 创建与 key 对应的 Dep 管理相关的 Watcher
  const dep = new Dep();
  //对数据进行劫持
  Object.defineProperty(obj, key, {
    get () {
      // 依赖收集
      Dep.target && dep.addDep(Dep.target)
      return val;
    },
    set (newVal) {
      if (newVal !== val) {
        // 如果 newVal 为 Object ,就需要对其响应式处理
        observe(newVal)
        val = newVal;
        // 通知更新
        dep.notify()
      }
    }
  })
}
class Observer {
  constructor(value) {
    this.value = value;
    if (typeof value === 'object') {
      this.walk(value)
    }
  }
  // 对象数据响应化
  walk (obj) {
    Object.keys(obj).forEach(key => {
      defineReactive(obj, key, obj[key])
    })
  }
}
// 观察者,保存更新函数。
class Watcher {
  constructor(vm, key, updateFn) {
    this.vm = vm
    this.key = key
    this.updateFn = updateFn
    Dep.target = this // 在静态属性上保存当前实例
    this.vm[this.key// 触发数据劫持 get
    Dep.target = null // 在读取属性 触发get后,依赖收集完毕,现在置空
  }
  update () {
    this.updateFn.call(this.vmthis.vm[this.key])
  }
}
// 订阅-发布,管理某个key相关所有Watcher实例
class Dep {
  constructor() {
    this.deps = []
  }
  addDep (dep) {
    this.deps.push(dep)
  }
  notify () {
    this.deps.forEach(dep => dep.update())
  }
}

相关链接

Vue(v2.6.14)源码解毒(预):手写一个简易版Vue

Vue(v2.6.14)源码解毒(一):准备工作

Vue(v2.6.14)源码解毒(二):初始化和挂载

Vue(v2.6.14)源码解毒(三):响应式原理

Vue(v2.6.14)源码解毒(四):更新策略

Vue(v2.6.14)源码解毒(五):render和VNode

Vue(v2.6.14)源码解毒(六):update和patch

Vue(v2.6.14)源码解毒(七):模板编译

如果觉得还凑合的话,给个赞吧!!!也可以来我的个人博客逛逛 www.mingme.net/