Vue 响应式的简单实现

一、前置知识

1-1 数据响应式

  • 数据响应式的数据指的是数据模型,数据模型仅仅是普通的 JavaScript 对象,而当我们修改数据时,视图会进行更新,是单向的

  • 数据响应式避免了繁琐的 DOM 操作,提高开发效率

1-2 双向绑定

  • vue 是一个 mvvm 框架,即数据双向绑定,即当数据发生变化的时候,视图也就发生变化,当视图发生变化的时候,数据也会跟着同步变化。数据双向绑定一定是对于UI控件来说的,非UI控件不会涉及到数据双向绑定

  • 在 vue 中,如果使用 vuex,实际上数据还是单向的,之所以说是数据双向绑定,这是对UI控件来说,对于处理表单,vue 的双向数据绑定用起来就特别舒服了,但即两者并不互斥, 在全局性数据流使用单项,方便跟踪,局部性数据流使用双向,简单易操作

  • vue 中是使用 v-model 在表单元素上创建双向数据绑定

1-3 数据驱动

  • 数据驱动是 Vue 最独特的特性之一,开发过程中仅需要关注数据本身,不需要关心数据是如何渲染到视图

二、数据响应式核心原理

2-1 vue 2.x 数据响应式原理

  • vue2 的响应式原理的核心是使用的 es5 中的 Object.defineProperty 来实现,当把一个普通的 JavaScript 对象传入 Vue 实例作为 data 选项,Vue 将遍历此对象所有的 property,并使用 Object.defineProperty 把这些 property 做数据劫持,转为 getter/setter ,进而追踪依赖,使得 vue 可以来监听对象的属性访问或者对象的属性修改

  • Object.defineProperty 的缺点也有很多,比如

  1. 要对对象深度监听,需要递归到底,一次性计算量大
  2. 无法监听新增、删除属性(需要 vue.set 和 vue.delete)
  3. 无法原生监听数组,需要特殊处理

简单数据劫持案例

// 模拟 Vue 中的 data 选项
let data = {
  msg: 'hello'
}

// 模拟 Vue 的实例
let vm = {}

// 数据劫持:当访问或者设置 vm 中的成员的时候,做一些干预操作
Object.defineProperty(vm, 'msg', {
  // 可枚举(可遍历)
  enumerable: true,
  // 可配置(可以使用 delete 删除,可以通过 defineProperty 重新定义)
  configurable: true,
  // 当获取值的时候执行
  get () {
    console.log('get: ', data.msg)
    return data.msg
  },
  // 当设置值的时候执行
  set (newValue) {
    console.log('set: ', newValue)
    if (newValue === data.msg) {
      return
    }
    data.msg = newValue
    // 数据更改,更新 DOM 的值
    document.querySelector('#app').textContent = data.msg
  }
})

// 测试
vm.msg = 'Hello World'
console.log(vm.msg)
复制代码

当需要劫持多个数据时候,就要使用遍历

// 模拟 Vue 中的 data 选项
let data = {
  msg: 'hello',
  count: 10
}

// 模拟 Vue 的实例
let vm = {}

proxyData(data)

function proxyData(data) {
  // 遍历 data 对象的所有属性
  Object.keys(data).forEach(key => {
    // 把 data 中的属性,转换成 vm 的 setter/setter
    Object.defineProperty(vm, key, {
      enumerable: true,
      configurable: true,
      get () {
        console.log('get: ', key, data[key])
        return data[key]
      },
      set (newValue) {
        console.log('set: ', key, newValue)
        if (newValue === data[key]) {
          return
        }
        data[key] = newValue
        // 数据更改,更新 DOM 的值
        document.querySelector('#app').textContent = data[key]
      }
    })
  })
}

// 测试
vm.msg = 'Hello World'
console.log(vm.msg)
复制代码

2-2 vue 3.x 数据响应式原理

  • vue 3.x 响应式原理的核心是使用ES6的 Proxy 进行数据响应化,Proxy 可以在目标对象上加一层拦截/代理,外界对目标对象的操作,都会经过这层拦截

proxy 实现对象代理的案例

// 模拟 Vue 中的 data 选项
let data = {
  msg: 'hello',
  count: 0
}

// 模拟 Vue 实例
let vm = new Proxy(data, {
  // 执行代理行为的函数
  // 当访问 vm 的成员会执行
  get (target, key) {
    console.log('get, key: ', key, target[key])
    return target[key]
  },
  // 当设置 vm 的成员会执行
  set (target, key, newValue) {
    console.log('set, key: ', key, newValue)
    if (target[key] === newValue) {
      return
    }
    target[key] = newValue
    document.querySelector('#app').textContent = target[key]
  }
})

// 测试
vm.msg = 'Hello World'
console.log(vm.msg)
复制代码

三、发布订阅模式

  • 发布订阅模式的三个核心是订阅者、发布者、事件中心

  • 我们假定,存在一个”信号中心”,某个任务执行完成,就向信号中心”发布”(publish)一个信号,其他任务可以向信号中心”订阅”(subscribe)这个信号,从而知道什么时候自己可以开始执行。这就叫做”发布/订阅模式”(publish-subscribe pattern)

  • Vue 中的自定义事件就是基于发布订阅模式的,可以认为调用 on的对象就会是订阅者,调用on 的对象就会是订阅者,调用 emit 的对象就是发布者

// eventBus.js
// 事件中心
let eventHub = new Vue()

// ComponentA.vue 发布者
addTodo: function () {
    // 发布消息(事件)
    eventHub.$emit('add-todo', { text: this.newTodoText })
    this.newTodoText = ''
}

// ComponentB.vue 订阅者
created: function () {
    // 订阅消息(事件)
    eventHub.$on('add-todo', this.addTodo)

}

复制代码

手写发布订阅模式

// 使用发布订阅模式,模拟 vue 的事件机制

// 事件触发器
class EventEmitter {
    constructor() {
        // 用来存储所有注册的事件,{ 'click': [fn1, fn2] , 'change':[fn] }
        this.subs = Object.create(null) 
    }
    
    // 注册事件 
    // eventType 事件类型 ,handler 事件处理函数
    $on(eventType, handler) {
        this.subs[eventType] = this.subs[eventType] || []
        this.subs[eventType].push(handler)
    }

    // 触发事件
    $emit(eventType) {
        if (this.subs[eventType]) {
          this.subs[eventType].forEach(handler => {
            handler()
          })
        }
    }
}

// 测试
let em = new EventEmitter()
em.$on('click', () => {
  console.log('click1')
})
em.$on('click', () => {
  console.log('click2')
})

em.$emit('click')
复制代码

四、观察者模式

  • vue 的响应式机制中使用了观察者模式

  • 观察者模式和发布订阅模式的区别就是,观察者模式没有事件中心,只有发布者和订阅者,而且发布者需要知道订阅者的存在

  • 发布订阅模式是由同一调度中心调用,因此发布者和订阅者不需要知道对方的存在,而观察者模式是由具体目标调度的,比如当事件触发,Dep就会去调用观察者的方法,所以观察者模式的发布者和订阅者是存在依赖的

  • 在观察者模式中,订阅者又称为观察者(watcher),所有的观察者都有一个 update 方法,当事件发生的时候就会调用所有订阅者的 update 方法。在 vue 中当数据发生变化的时候,会调用观察者的 update 方法去更新视图

  • 在观察者模式中,观察者的 update 方法是由发布者去调用的,发布者又称为目标(Dep),当事件发生的时候,是有发布者去通知所有观察者,所以发布者内部会有一个属性 subs 数组,来记录所有的观察者,还会有一个 addSub 方法,添加观察者到数组中,还有一个 notify 方法,用来当事件发生时候,调用所有观察者的 update 方法

手写观察者模式

 // 发布者-目标
class Dep {
  constructor () {
    this.subs = [] // 记录所有的订阅者
  }
  // 添加订阅者
  addSub (sub) {
    // 判断订阅者必须要有 update 方法
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }
  // 发布通知
  notify () {
    this.subs.forEach(sub => {
      sub.update()
    })
  }
}
// 订阅者-观察者
class Watcher {
  update () {
    console.log('update')
  }
}

// 测试
let dep = new Dep()
let watcher = new Watcher()

dep.addSub(watcher)

dep.notify()
复制代码

五、模拟 Vue 响应式原理

大致结构分为五个模块

  1. Vue: 把 data 中的成员注入到 Vue 实例中,并且把 data 中的成员转成 getter/setter
  2. Observer:对数据对象的所有属性进行监听,如有变动可拿到最新值并通知 Dep
  3. Compiler:解析每个元素中的指令/插值表达式,并替换成相应的数据
  4. Dep:添加观察者(watcher),当数据变化通知所有观察者
  5. Watcher:数据变化更新视图

image.png

5-1 Vue 的实现

功能:

  1. 负责接收初始化的参数(选项)
  2. 负责把 data 中的属性注入到 Vue 实例,转换成 getter/setter
  3. 负责调用 observer 监听 data 中所有属性的变化
  4. 负责调用 compiler 解析指令/插值表达式
// 小规定:所有下划线开头的成员都是私有成员,所有$开头都是实例成员
// vue.js
class Vue {
  constructor (options) {
    // 1. 通过属性保存选项的数据
    this.$options = options || {}
    this.$data = options.data || {}
    this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el
    
    // 2. 把 data 中的成员转换成 getter 和 setter ,注入到 vue 实例中
    // 主要是为了可以让vue实例直接获取到 data 中的数据,而不是需要在通过 vm.data
    this._proxyData(this.$data)
    
    // 3. 调用 observer 对象,监听数据的变化
    new Observer(this.$data)
    
    // 4. 调用 compiler 对象,解析指令和差值表达式
    new Compiler(this)
  }
  
  _proxyData (data) {
    // 遍历 data 中的所有属性
    Object.keys(data).forEach(key => {
      // 把 data 的属性注入到 vue 实例中
      Object.defineProperty(this, key, {
        enumerable: true,
        configurable: true,
        get () {
          return data[key]
        },
        set (newValue) {
          if (newValue === data[key]) {
            return
          }
          data[key] = newValue
        }
      })
    })
  }
}
复制代码

5-2 Observer 实现

功能:

  1. 负责把 data 选项中的属性转换成响应式数据
  2. data 中的某个属性也是对象,把该属性转换成响应式数据
  3. 数据变化发送通知
class Observer {
  constructor (data) {
    this.walk(data)
  }
  
  // 遍历 data 中的所有属性
  walk (data) {
    // 1. 判断 data 是否是对象
    if (!data || typeof data !== 'object') {
      return
    }
    // 2. 遍历 data 对象的所有属性
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
    })
  }
  
  // 定义响应式数据,把传过来的属性转化为 getter/setter
  defineReactive (obj, key, val) {
    let that = this
    // 为每一个属性创建一个 dep 对象,作用是负责收集依赖,并发送通知
    let dep = new Dep()
    // 如果 val 是对象,把 val 内部的属性转换成响应式数据
    this.walk(val)
    Object.defineProperty(obj, key, {
      enumerable: true, // 可枚举
      configurable: true, // 可配置
      get () {
        // 收集依赖(就是把观察者对象添加到subs数组中)
        Dep.target && dep.addSub(Dep.target)
        // 这里之所以 return 的是 val,而不是 obj[key],
        // 是因为返回 obj[key] 的话会再次调用该属性的 get 方法,出现死递归,导致堆栈溢出
        return val
      },
      set (newValue) {
        if (newValue === val) {
          return
        }
        val = newValue
        // 如果 newValue 是对象,把 newValue 内部的属性转换成响应式数据
        that.walk(newValue)
        // 发送通知
        dep.notify()
      }
    })
  }
}
复制代码

5-3 Compiler 实现

功能:

  1. 负责编译模板,解析指令/插值表达式
  2. 负责页面的首次渲染
  3. 当数据变化后重新渲染视图
class Compiler {
  constructor (vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }
  
  // 编译模板,处理文本节点和元素节点
  compile (el) {
    // childNodes 是子节点集合,是一个伪数组
    let childNodes = el.childNodes
    // 遍历 dom 对象所有节点
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        // 处理文本节点,解析差值表达式
        this.compileText(node)
      } 
      else if (this.isElementNode(node)) {
        // 处理元素节点,解析指令
        this.compileElement(node)
      }

      // 判断 node 节点,是否有子节点,如果有子节点,要递归调用 compile
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  
  // 编译元素节点,处理指令
  compileElement (node) {
    // 遍历 dom 所有的属性
    Array.from(node.attributes).forEach(attr => {
      // 获取属性名字
      let attrName = attr.name
      // 判断是否是指令
      if (this.isDirective(attrName)) {
        // 截取指令名字 v-text --> text
        attrName = attrName.substr(2)
        // 获取属性的值
        let key = attr.value
        this.update(node, key, attrName)
      }
    })
  }

  update (node, key, attrName) {
    let updateFn = this[attrName + 'Updater']
    updateFn && updateFn.call(this, node, this.vm[key], key)
  }

  // 处理 v-text 指令
  textUpdater (node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  
  // 处理 v-model 指令
  modelUpdater (node, value, key) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    // 双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }

  // 编译文本节点,处理差值表达式
  compileText (node) {
  
    // 匹配差值表达式的正则 {{}}
    let reg = /\{\{(.+?)\}\}/
    // 获取文本节点的内容
    let value = node.textContent
    
    // 判断是否匹配正则表达式
    if (reg.test(value)) {
      // 获取到正则括号中的内容
      let key = RegExp.$1.trim() 
      // 替换差值表达式中的值
      node.textContent = value.replace(reg, this.vm[key])
      // 创建watcher对象,当数据改变更新视图
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }
  }
  
  // 判断元素属性是否是指令
  isDirective (attrName) {
    return attrName.startsWith('v-')
  }
  
  // 判断节点是否是文本节点
  isTextNode (node) {
    return node.nodeType === 3
  }
  
  // 判断节点是否是元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
}
复制代码

5-4 Dep 实现

功能:

  1. 收集依赖,添加观察者(watcher)
  2. 通知所有观察者

image.png

class Dep {
  constructor () {
    // 存储所有的观察者
    this.subs = []
  }
  // 添加观察者
  addSub (sub) {
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }
  // 发送通知,通知所有观察者
  notify () {
    this.subs.forEach(sub => {
      sub.update()
    })
  }
}
复制代码

5-5 Watcher 实现

功能:

  1. 当数据变化触发依赖, dep 通知所有的 Watcher 实例更新视图
  2. 自身实例化的时候往 dep 对象中添加自己

image.png

class Watcher {
  constructor (vm, key, cb) {
    this.vm = vm
    // data中的属性名称
    this.key = key
    // 回调函数负责更新视图
    this.cb = cb

    // 把 watcher 对象记录到 Dep 类的静态属性 target
    Dep.target = this
    // 触发 get 方法,在 get 方法中会调用 addSub
    this.oldValue = vm[key]
    Dep.target = null
  }
  // 当数据发生变化的时候更新视图
  update () {
    let newValue = this.vm[this.key]
    if (this.oldValue === newValue) {
      return
    }
    this.cb(newValue)
  }
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享