Vue响应式原理

数据驱动

// 在模拟vue响应式原理之前:需要了解:数据驱动、响应式的核心原理;发布订阅模式和观察者模式

// 数据响应式:数据响应式中的数据就是数据模型,基于vue开发的数据模型就是普通的JavaScript对象,当我们修改数据时,视图会进行更新,避免了繁琐的DOM操作,提高开发效率

// 双向绑定:
// 1、数据改变,视图改变;视图改变,数据也随之改变
// 2、可以使用v-module在表单元素上创建双向数据绑定

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

Vue数据响应式的核心原理

// vue 2.x深入响应式原理:https://cn.vuejs.org/v2/guide/reactivity.html
// vue 2.x 主要是用到了Object.defineProperty

// vue 3.x  Proxy 直接监听对象,而非属性 es6新增,ie不支持,性能由浏览器优化  Proxy

Vue2.x的响应式核心原理模拟

<!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>defineProperty</title>
</head>

<body>
  <div id="app">
    hello
  </div>
  <script>
    // 模拟 Vue 中的 data 选项
    let data = {
      msg: 'hello'
    }
    // 模拟 Vue 的实例
    let vm = {}

    // 数据劫持:当访问或者设置 vm 中的成员的时候,做一些干预操作
    // 第一个参数是对象;第二个是给vm增加的属性;第三个是属性描述符(通过属性描述符可以给属性设置get和set方法)
    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)
  </script>
</body>

</html>

// 当有多个成员的时候
<!DOCTYPE html>
<html lang="en">

<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>defineProperty 多个成员</title>
</head>

<body>
  <div id="app">
    hello
  </div>
  <script>
    // 模拟 Vue 中的 data 选项   data中有多个属性;采用遍历来分别对每个属性进行get/set
    let data = {
      msg: 'hello',
      count: 10
    }

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

    proxyData(data)

    function proxyData(data) {
      // 遍历 data 对象的所有属性  Object.keys(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)
  </script>
</body>

</html>

Vue3.x的响应式核心原理模拟

<!DOCTYPE html>
<html lang="en">

<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>Proxy</title>
</head>

<body>
  <div id="app">
    hello
  </div>
  <script>
    // 模拟 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)
  </script>
</body>

</html>

Vue自定义事件

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue 自定义事件</title>
</head>

<body>
  <script src="./js/vue.js"></script>
  <script>
    // Vue 自定义事件
    let vm = new Vue()
    // { 'click': [fn1, fn2], 'change': [fn] }

    // 注册事件(订阅消息)  $once 绑定一个自定义事件,该事件只能被触发一次,$off 移除自定义事件监听器
    vm.$on('dataChange', () => {
      console.log('dataChange')
    })

    vm.$on('dataChange', () => {
      console.log('dataChange1')
    })
    // 触发事件(发布消息)
    vm.$emit('dataChange')
  </script>
</body>

</html>

发布订阅模式

<!DOCTYPE html>
<html lang="cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>发布订阅模式</title>
</head>

<body>
  <script>
    // 事件触发器
    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')
  </script>
</body>

</html>

观察者模式

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>观察者模式</title>
</head>

<body>
  <script>
    // 观察者没有事件中心。 
    // 观察者就是订阅者;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()
        })
      }
    }
    // 订阅者-观察者  
    // 每个观察者都约定有一个update方法
    class Watcher {
      update() {
        console.log('update')
      }
    }

    // 测试
    let dep = new Dep()
    let watcher = new Watcher()
    dep.addSub(watcher)
    dep.notify()
  </script>
</body>

</html>

实现一个最小版本的Vue

最小版本的vue的整体结构:

Vue类型:负责把data中的成员注入到vue实例中并且转换为get/set;vue内部会调用Observer/Compiler,observer是数据劫持,能够对data中的属性进行监听,如果数据发生变化,会将最新的结果通知dep;Compiler的作用是解析每个元素中的的指令和插值表达式并替换成相应的数据;Dep是目标,作用是添加观察者,当数据变化时,通知所有的观察者;watcher的update方法负责更新视图

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.js

class Observer {
  // observer就是把data中的数据转换为get/set

  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])
    })
  }
  // val 是obj对象key属性对应的val值
  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 () {
        // 收集依赖
        // 收集依赖的时候先看看有没有观察者对象(target)
        Dep.target && dep.addSub(Dep.target)
        // 如果这里是obj[key]会产生死递归问题
        return val
      },
      set (newValue) {
        if (newValue === val) {
          return
        }
        val = newValue
        // 赋值的也是一个对象就需要加上这个;来让复制的对象的属性也转换为响应式数据
        console.log(this, '这个是this');
        that.walk(newValue)
        // 发送通知
        dep.notify()
      }
    })
  }
}

Compiler.js

class Compiler {
  constructor (vm) {
    this.el = vm.$el
    this.vm = vm
    // 当构造函数执行完毕后;希望能够立刻开始编译模板;所以调用compile
    this.compile(this.el)
  }
  // 编译模板,处理文本节点和元素节点
  compile (el) {
    // console.log(el, '要获取他的所有子节点,children是子元素', el.childNodes, '0000', el.children);
    // el.childNodes是一个伪数组;想要遍历数组的话;可以通过Array.from(childNodes)来转换为数组
    let childNodes = el.childNodes
    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) {
    // 获取所有属性节点
    console.log(node.attributes)
    // 遍历所有的属性节点
    Array.from(node.attributes).forEach(attr => {
      // 判断是否是指令
      let attrName = attr.name
      let key = attr.value
      if (this.isDirective(attrName)) {
        // v-text --> text
        attrName = attrName.substr(2)

        this.update(node, key, attrName)
      } else if (this.isHandleEvent(attrName)) {
        attrName = attrName.substr(1)
        this.update(node, key, 'on', attrName)
      }
    })
  }

  // node:要更新的元素;key:data中属性的名字(msg,count),attrName:方法的前缀(text;model)
  update (node, key, attrName, event) {
    // 调用处理v-函数
    let updateFn = this[attrName + 'Updater']
    // 这个this就是compiler对象
    let value = attrName != 'on' ? this.vm[key] : this.vm.$options.methods[key]  // on在methods中对应的方法名
    updateFn && updateFn.call(this, node, value, key, event)
  }

  // 处理 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指向compiler对象
      this.vm[key] = node.value
    })
  }
  // v-html
  htmlUpdater (node, value, key) {
    node.innerHTML = value
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }

  // v-on/@
  onUpdater (node, value, key, event) {
    node.addEventListener(event, value)
  }


  // 编译文本节点,处理差值表达式
  compileText (node) {
    // console.dir(node)
    // {{  msg }}
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    if (reg.test(value)) {
      // RegExp.$1可以获取reg匹配到的第一个内容;$2可以获取第二个内容  .trim()去除收尾空白字符
      let key = RegExp.$1.trim()
      // 把msg属性名换成对应的值
      node.textContent = value.replace(reg, this.vm[key])

      // 创建watcher对象,当数据改变更新视图
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }

  }
  // 判断元素属性是否是指令
  isDirective (attrName) {
    // 判断是否以什么开头;以v-开头返回true;否则返回false
    return attrName.startsWith('v-')
  }
  // 判断元素属性是否以@开头
  isHandleEvent (attrName) {
    return attrName[0] === '@'
  }

  // 判断节点是否是文本节点
  isTextNode (node) {
    // nodeType是节点的类型;如果是3的话就是文本节点;等于1就是元素节点
    return node.nodeType === 3
  }
  // 判断节点是否是元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
}

Dep.js

class Dep {
  // 作用:收集依赖;发送通知
  // 构造函数
  constructor () {
    // 存储所有的观察者
    this.subs = []
  }
  // 添加观察者
  addSub (sub) {
    // 约定所有的观察者都有个update方法
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }
  // 发送通知
  notify () {
    this.subs.forEach(sub => {
      sub.update()
    })
  }
}

Watcher.js

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)
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值