vue.js响应式原理

2021-02-28  本文已影响0人  lowpoint

vue2响应式原理主要通过 Object.fefineProperty

当把一个普通的js对象传入 Vue 实例作为 data 选项,Vue将遍历此对象所有的属性,并使用 Object.fefineProperty 把这些属性全部转为 getter/setter 。 Object.defineProperty 是ES5中一个无法 shim 的特性,这也是Vue 不支持IE8 以及更低版本浏览器的原因。

// 模拟 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'

vue3响应式原理主要通过 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]
      }
    })

发布订阅模式

// 事件触发器
    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()
图片.png

手写一个简单的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实例中
    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
        }
      })
    })
  }
}

Observer

class Observer{
  
  constructor(data){
    this.walk(data)
  }
  //遍历对象的所有属性
  walk(data){
    //1.判断data是否为对象
    if(!data || typeof data !== 'object') return 
    //2.遍历对象的所有属性
    Object.keys(data).forEach(key=>{
      this.defineReactive(data,key,data[key])
    })
  }
  //调用 Object.definePorperty 将属性转换为getter与setter
  //params:1.object 2.key 3.val
  defineReactive(obj,key,val){

    let that = this
    //收集依赖,并且发送通知
    let dep = new Dep()  //通过后面Dep类实现
    //val为对象 此时也要把val内部对象属性转为getter 与setter
    this.walk(val)

    Object.defineProperty(obj,key,{
      enumerable:true,
      configurable:true,
      get(){
        Dep.target && dep.addSub(Dep.target) //收集依赖
        return val
        //不返回 obj[key] 因为 obj[key] 会访问obj 一直出发get() 栈溢出
      },
      set(newval){
        if(newval === val) return 
        val = newval
        //新赋值
        that.walk(newval)
         //发送通知
        dep.notify() //通过后面dep类实现
      }
    })
  }
}

Compiler

class Compiler {
  //传入vue实例
  constructor(vm) {
    this.el = vm.$el
    this.vm = vm

    this.compile(this.el)
  }
  //编译模板 处理文本与元素节点
  compile(el) {
    //遍历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) {
    //遍历所有属性节点
    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 fn = this[attrname + `Updater`]
    fn && fn.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绑定input事件
    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
  }
}

Dep(Dependency)

class Dep {
  constructor() {
    //存储所有观察者
    this.subs = []
  }
  //添加观察者
  addSub(sub) {
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }
  //发布通知
  notify() {
    this.subs.forEach(sub => {
      sub.update()
    })
  }
}
图片.png

Watcher

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

    //将 Watcher 对象记录在Dep类的静态属性 target
    Dep.target = this
    //触发 get 方法,在fet方法中调用addSub
    this.oldValue = vm[key] //vm[key]会访问 get() 将 watcher对象存放在 target 中

    Dep.target = null //防止重复添加
  }

  //数据发生变化的时候更新视图
  update() {
    let newValue = this.vm[this.key]
    if (this.oldValue === newValue) return
    this.cb(newValue)
  }
}
图片.png

Virtual DOM

虚拟dom就是用普通的js对象来描述 DOM 对象
真实dom成员复杂,虚拟dom可以用简洁的方式来表示实现真实dom,创建虚拟dom开销小。

虚拟dom库

Snabbdom

cnpm i snabbdom

import { init } from 'snabbdom/build/package/init'
import { h } from 'snabbdom/build/package/h'

const patch = init([])

// 第一个参数:标签+选择器
// 第二个参数:如果是字符串就是标签中的文本内容
let vnode = h('div#container.cls', {
  hook: {
     //钩子函数
    init(vnode) {
      console.log(vnode.elm)
    },
    create(emptyNode, vnode) {
      console.log(vnode.elm)
    }
  }
}, 'Hello World')

// 嵌套子元素
// let vnode = h('div#container', [
//   h('h1', 'Hello Snabbdom'),
//   h('p', '这是一个p')
// ])

let app = document.querySelector('#app')

// patch第一个参数:旧的 VNode,可以是 DOM 元素
// patch第二个参数:新的 VNode
// 返回新的 VNode
// patch对比两个vnode 将差异更新到真实node上

let oldVnode = patch(app, vnode)
// 清除div中的内容 
 // patch(oldVnode, h('!')) //空注释节点

Snabbdom 模块

使用模块

Snabbdom 核心

patch 整体过程分析

上一篇下一篇

猜你喜欢

热点阅读