深入了解VueJs响应式原理

376 阅读3分钟
  • 数据驱动
  • 响应式的核心原理
  • 发布订阅模式和观察者模式

数据驱动

  • 数据响应式、双向绑定、数据驱动

  • 数据响应式

    • 数据模型仅仅是普通的Javascript对象,当我们修改数据时,视图会进行更新,避免了繁琐的dom操作,提高开发效率
  • 双向绑定

    • 数据改变,视图改变;视图改变,数据也随之改变
    • 我们可以用v-model在表单元素上创建双向数据绑定
  • 数据驱动是vue最独特的特性之一

    • 开发过程中只需要关注数据本身,不需要关心数据是如何渲染到视图的

数据响应式的核心原理

vue2

Object.defineproperty

let data = {
  msg: 'hello'
}
let vm = {}
// 数据劫持,当访问或设置vm中的成员的时候,做一些干预操作
Object.defineProperty(vm, 'msg', {
  enumerable: true,
  configurable: true,
  get() {
    return data.msg
  }
  set(newValue) {
    if (newValue === data.msg) {
      return
    }
    data.msg = newValue
    
    document.querySelector('#app').textContent = data.msg  
  }
})
let data = {
  msg: 'hello',
  count: 100
}
let vm = {}
// 数据劫持,当访问或设置vm中的成员的时候,做一些干预操作
Object.keys(data).forEach(key => {
  Object.defineProperty(vm, 'msg', {
      enumerable: true,
      configurable: true,
      get() {
        return data[key]
      }
      set(newValue) {
        if (newValue === data[key]) {
          return
        }
        data[key] = newValue
        document.querySelector('#app').textContent = data[key]
      }
    })
})

vue3

代理整个对象

let data = {
  msg: 'hello',
  count: 100
}
let vm = {}
// 数据劫持,当访问或设置vm中的成员的时候,做一些干预操作
let vm = new Proxy(vm, {
  enumerable: true,
  configurable: true,
  get(target, key) {
    return target[key]
  }
  set(target, key, newValue) {
    if (target[key] === newValue) {
      return
    }
    target[key] = newValue
    
    document.querySelector('#app').textContent = data.msg  
  }
})

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

发布/订阅模式

  • 订阅者
  • 发布者
  • 信号中心

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

// VUe的自定义事件
let vm = new Vue()

// 订阅消息
vm.$on('dataChange', () => {
  console.log('dataChange')
})
vm.$on('dataChange', () => {
  console.log('dataChange1')
})
// 发布消息
vm.$emit('dataChange')
// 兄弟组件通信过程
// eventBus
let eventHub = new Vue()

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

// componentB.vue  订阅消息
created() {
  eventHub.$on('add-todo', this.addTodo)
}

原理

// 事件触发器
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('click')
})
em.$emit('click')

观察者模式

  • 观察者(订阅者)Watcher

    • update():当事件发生时,具体要做的事
  • 目标(发布者)

    • subs数组:存储所有的观察者
    • addSub():添加观察者
    • notify():当时间发生时,调用所有观察者的update()方法

没有事件中心

// 发布者目标
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()
  • 观察者模式由具体目标调度,比如当事件触发,Dep就会去调用观察者的方法,所以观察者模式的订阅者和发布者之间是存在依赖的
  • 发布/订阅模式由统一调度中心调用,因此发布者和订阅者不需要知道对方存在

手写vue响应式原理源码

功能

  • 负责接收初始化的参数
  • 把data中的属性注入到vue中,装换成getter和setter
  • observer监听data中所有属性的变化
  • 负责调用compiler解析指令/插值表达式

模板

<!DOCTYPE html>
<html lang="cn">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Vue 基础结构</title>
</head>
<body>
  <div id="app">
    <h1>差值表达式</h1>
    <h3>{{ msg }}</h3>
    <h3>{{ count }}</h3>
    <h1>v-text</h1>
    <div v-text="msg"></div>
    <h1>v-model</h1>
    <input type="text" v-model="msg">
    <input type="text" v-model="count">
  </div>

  <script src="./js/dep.js"></script>
  <script src="./js/watcher.js"></script>
  <script src="./js/compiler.js"></script>
  <script src="./js/observer.js"></script>
  <script src="./js/vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        msg: 'Hello Vue',
        count: 20,
      }
    })
  </script>
</body>
</html>

js/vue.js

class Vue {
  constructor(options) {
    // 通过此属性保存选项中的数据
    this.$options = options || {}
    this.$data = options.data || {}
    this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el
    // 把data中的成员转化为setter和getter
    this._proxyData(this.$data)
    // observer监听数据的变化
    new Observer(this.$data)
    // compiler解析指令和差值表达式
    new Compiler(this)
  }
  _proxyData(data) {
    // 把data中的属性注入到vue中
    Object.keys(data).forEach(key => {
      Object.defineProperty(this, key, {
        configurable: true,
        enumerable: true,
        get() {
          return data[key]
        },
        set(newValue) {
          if (newValue === data[key]) {
            return
          }
          data[key] = newValue
        }
      })
    })
  }
}

js/observer.js

class Observer {
  constructor(data) {
    this.walk(data)
  }
  walk(data) {
    if (!data || typeof data !== 'object') return
    Object.keys(data).forEach(key => {
        this.defineReactive(data, key, data[key])
    })
  }
  defineReactive(obj, key, val) {
    const that = this
    // 负责收集依赖
    let dep = new Dep()
    this.walk(val)
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      get() {
        Dep.target && dep.addSub(Dep.target)
        return val
      },
      set(newValue) {
        if (newValue === val) {
          return
        }
        val = newValue
        that.walk(newValue)
        // 发送通知
        dep.nodify()
      }
    })
  }
}

js/compiler.js

class Compiler {
  constructor(vm) {
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }
  // 编译模板,处理文本节点和元素节点
  compile(el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        this.compileElement(node)
      }
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  // 编译元素节点,处理指令
  compileElement(node) {
    // console.log( Array.from(node.attributes))
    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, atterName) {
    let updateFn = this[atterName + '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) {
    const reg = /{{(.+?)}}/   // ()分组
    let value = node.textContent
    if (reg.test(value)) {
      // RegExp获取最近使用正则的分组
      const 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
  }
}

js/dep.js

class Dep {
  constructor() {
    this.subs = []
  }
  // 添加观察者
  addSub(sub) {
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }
  // 发送通知
  nodify() {
    this.subs.forEach(sub => {
      sub.update()
    })
  }
}

js/watcher.js

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm
    this.key = key
    // 更新视图
    this.cb = cb
    // 把watcher记录到Dep类的静态属性target
    Dep.target = this
    this.oldValue = vm[key]
    Dep.target = null
  }
  // 当数据变化更新视图
  update() {
    let newValue = this.vm[this.key]
    if (this.oldValue === newValue) {
      return
    }
    this.cb(newValue)
  }
}