当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue源码学习之Vue响应式数据实现

Vue源码学习之Vue响应式数据实现

2020年07月14日  | 移动技术网IT编程  | 我要评论

Vue响应式数据

说到Vue源码必定会说到Vue的双向数据绑定,这里简单介绍下Vue响应式数据的实现,Vue内响应式的实现实际上时依据Object.defineProperty 与观察者模式实现的,但是很多人可能会将发布订阅模式与观察者模式搞混,这里也简单介绍两者的区别。

发布订阅模式与观察者模式

  • 发布订阅模式 :一个事件中心,有一个事件收集器属性,注册事件,触发事件的方法,通过事件注册将需要执行的方法添加到事件收集器,当触发事件执行时间收集器中的所有方法
  • 观察者模式 :没有事件中心,只有发布者与观察者,发布者有依赖收集器,收集所有订阅者,添加订阅者方法,发布通知的方法,让所有订阅者执行自身的update操作,观察者有一个update方法

发布订阅模式

     // 事件触发器
    class EventEmitter {
      constructor () {
        // { 'click': [fn1, fn2], 'change': [fn] }
        this.subs = Object.create(null)
      }

      // 注册事件
      $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')

观察者模式

  // 发布者-目标
  class Dep {
    constructor () {
      // 记录所有的订阅者
      this.subs = []
    }
    // 添加订阅者
    addSub (sub) {
      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

实例化Vue的时候,我们需要将data中的数据转换为相应式数据,并注入到Vue实例上

  1. 通过属性保存选项的数据
  2. 把data中的成员转换成getter和setter,注入到vue实例中
  3. 调用observer对象,监听数据的变化(对data中的数据进行循环遍历,转换成getter setter)
  4. 调用compiler对象,解析指令和差值表达式(首次渲染)
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实例中
      this._proxyData(this.$data)
      // 3. 调用observer对象,监听数据的变化
      new Observer(this.$data)
      // 4. 调用compiler对象,解析指令和差值表达式
      new Compiler(this)

  }
  _proxyData(data) {
    Object.keys(data).forEach(key => {
      Object.defineProperty(this, key, {
        enumerable: true, //可枚举
        configurable: true, //可配置
        get () {
          return data[key]
        },
        set(newValue) {
          if (newValue === data[key]) {
            return
          }
          data[key] = newValue
        }
      })
    })
  }
}

Observer

Observer用于将data中的数据循环遍历全部转换为响应式数据,同时在触发getter时收集观察者,触发setter时触发Dep实例的notify方法更新视图

  1. 判断data是否是对象
  2. 遍历data对象的所有属性转换成响应式数据(深度遍历)
  3. 给每个data上的属性(如果属性是对象,二级属性也一样)定义一个 Dep对象负责收集依赖,并发送通知
  4. 每个数据转换成响应式数据之后,触发get方法时Dep使用addSub收集Watcher
  5. 每个数据转换成响应式数据之后,set时触发Dep的notify方法,通知所有Watcher执行update更新视图
  6. 注意 set时传入的数据如果是对象需要对其进行处理,遍历对象的所有属性转换成响应式数据(深度遍历)
class Observer {
  constructor (data) {
    this.walk(data)
  }
  walk (data) {
    // 1. 判断data是否是对象
    if (!data || typeof data !== 'object') {
      return
    }
    // 2. 遍历data对象的所有属性
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
    })
  }
  defineReactive (obj, key, val) {
    let that = this
    // 负责收集依赖,并发送通知
    let dep = new Dep()
    // 如果val是对象,把val内部的属性转换成响应式数据
    this.walk(val)
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get () {
        // 收集依赖 由Watcher中触发
        Dep.target && dep.addSub(Dep.target)
        return val
      },
      set (newValue) {
        if (newValue === val) {
          return
        }
        val = newValue
        that.walk(newValue)
        // 发送通知
        dep.notify()
      }
    })
  }
}

Compiler

Compiler 主要用于响应式数据的渲染,解析指令和差值表达式

  1. 构造函数获得vm的dom节点,进行编译
  2. 通过childNodes获得所有子节点(文本节点,元素节点),分别处理,如果节点中还有子节点 递归调用
  3. 编译文本节点,处理差值表达式(正则匹配插值表达式,如果匹配,将差值表达式替换为对应数据,同时创建watcher对象,watcher对象有三个参数,vue实例,对应属性值, 回调函数)
  4. 编译元素节点,获取元素节点所有属性节点(普通属性,指令v-开头),普通属性不处理,对不同指令进行不同的处理,在指令处理过程中创建watcher对象,watcher对象有三个参数,vue实例,对应属性值, 回调函数
class Compiler {
  constructor(vm) {
    console.log(vm)
    this.vm = vm
    this.el = vm.$el
    this.compile(this.el)
  }
  compile(el) {
    let nodes = el.childNodes;
    Array.from(nodes).forEach(node => {
      if (this.isElementNode(node)) {
        this.compileElement(node)
      } else if (this.isTextNode(node)) {
        this.compileText(node)
      }
      // 判断node节点,是否有子节点,如果有子节点,要递归调用compile
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  compileElement(node) {
      let attrs = node.attributes;
      let onReg = /^on/
      Array.from(attrs).forEach(attr => {
        if (this.isDirective(attr.name)) {
          // v-text --> text
          let attrName = attr.name.substr(2)
          if (attr.name.startsWith('@')) {
            attrName = attr.name.replace(/\@/, 'v-on:').substr(2)
          }
           
          let key = attr.value
          if (onReg.test(attrName)) { //v-on
            attrName = attrName.substr(3)
            this.updateOn(node, key, attrName)
          } else {// other
            this.update(node, key, attrName)
          }
        }
      })
  }
  update(node, key, attrName) {
    let updateFn = this[attrName + 'Update']
    updateFn && updateFn.call(this, node, this.vm[key], key)
  }
  //v-on事件
  updateOn(node, key, attrName) {
    let eventReg = /^\[(.*)\]$/ 
    if (eventReg.test(attrName)) {
      attrName = this.vm[RegExp.$1]
    }
    let oldEvent = attrName
    new Watcher(this.vm, RegExp.$1, (newValue) => { //响应动态事件
      node.removeEventListener(oldEvent, this.vm.$options.methods[key]) //清除上次事件
      oldEvent = newValue; //记录上次注册的事件名
      node.addEventListener(newValue, this.vm.$options.methods[key]) //注册事件
    })
    node.addEventListener(attrName, this.vm.$options.methods[key])//注册事件
  }

  textUpdate(node, value, key) {
    node.textContent = value
    // 创建watcher对象,当数据改变更新视图
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  
  modelUpdate(node, value, key) {
    node.value = value
    // 创建watcher对象,当数据改变更新视图
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    // 双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }
  //v-html
  htmlUpdate(node, value, key) {
    console.log(node)
    node.innerHTML = value
    // 创建watcher对象,当数据改变更新视图
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }

  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-') || attrName.startsWith('@')
  }
  // 判断节点是否是文本节点
  isTextNode (node) {
    return node.nodeType === 3
  }
  // 判断节点是否是元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
}

Dep

  1. 有一个subs属性存储对应属性的观察者(每个相应数据都会创建一个Dep实例)
  2. 一个addSub方法添加观察者到subs数组内,在首次编译compile时会在每个使用到相应数据的地方创建一个Watcher对象,Watcher对象内会获取对应属性的数据触发get方法,get方法会执行dep.addSub方法将该Watcher收集
  3. 一个notify方法,用来触发subs中所有Watcher的update方法,在set对应响应数据时触发
class Dep {
  constructor () {
    // 存储所有的观察者
    this.subs = []
  }
  // 添加观察者
  addSub (sub) {
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }
  // 发送通知
  notify () {
    this.subs.forEach(sub => {
      sub.update()
    })
  }
}

Watcher

  1. 存储三个传入的参数,把watcher对象记录到Dep类的静态属性target,获取对应属性的值触发get方法,在get方法中会调用addSub将Watcher添加到依赖,清空Dep类的静态属性target
  2. 当数据发生变化的时候Dep会执行notify方法,遍历所有Watcher执行他的update方法(执行的是Watcher注册时的回调函数,视图如何更新定义在回调函数中)更新视图(判断注册时对应属性的值与更新视图后的值是否一致,一致则不更新)
class Watcher {
  constructor (vm, key, cb) {
    this.vm = vm
    // data中的属性名称
    this.key = key
    // 回调函数负责更新视图
    this.cb = cb

    // 把watcher对象记录到Dep类的静态属性target
    Dep.target = this
    // 触发Observer中的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)
  }
}

本文地址:https://blog.csdn.net/weixin_44213825/article/details/107292528

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网