大前端【3-1-2笔记】响应式原理

一、回顾

1、数据响应式

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

2、双向绑定

  • 数据改变,视图改变;
  • 视图改变,数据改变;
  • 可以使用v-model在表单元素上创建双向数据绑定

3、数据驱动

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

二、响应式原理

当我们吧一个普通的JS对象传入vue实例作为data选项,vue将遍历此对象所有的属性,并使用Object.defineProperty把这些属性全部转化为getter/setter。Object.defineProperty是ES5中不可shim的特性,这就是Vue不支持IE8及更低浏览器的原因。

1、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 中的成员的时候,做一些干预操作
    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 选项
    let data = {
    
    
      msg: 'hello',
      count: 10
    }

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

    proxyData(data)

    function proxyData(data) {
    
    
      // 遍历 data 对象的所有属性
      Object.keys(data).forEach(key => {
    
    
        // 把 data 中的属性,转换成 vm 的 getter/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>
2、vue3.0响应式实现原理

监听对象

<!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>

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

1、发布订阅模式
  • 发布/订阅模式

    订阅者

    发布者

    信号中心

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

模拟发布/订阅模式

<script>
        //事件触发器
        class EventEmitter {
    
    
            constructor () {
    
    
                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>
2、观察者模式

观察者(订阅者)–Watcher

  • update():当事件发生时,具体要做的事情。

目标(发布者)–Dep

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

没有事件中心

实现方式:

<script>
        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 watch = new Watcher()
        let dep = new Dep()
        dep.addSub(watch)
        dep.notify() 
    </script>
3、二者的区别
  • 观察者模式是由具体目标调度,比如当事件触发,Dep就会去调用观察者的方法,所以观察者模式的订阅者和发布者是存在依赖的。
  • 发布/订阅模式是由统一调度中心调用,因此发布者和订阅者不需要知道对方的存在。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vz4SINCZ-1597762329049)(C:\Users\张艳杰\AppData\Roaming\Typora\typora-user-images\1596374818874.png)]

四、模拟Vue响应式原理

1、整体分析
  • Vue基本结构

  • 打印Vue实例观察

  • 整体结构

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8iOQv0AM-1597762329053)(C:\Users\张艳杰\AppData\Roaming\Typora\typora-user-images\1596375619476.png)]

2、Vue

把data中的成员注入到Vue实例,并且把data中的成员转成gettter、setter

  • 功能

    • 负责结构初始化的参数(选项)
    • 负责把data中的属性注入到Vue实例,转化成getter、setter
    • 负责调用observer监听data中的所有属性的变化
    • 负责调用compiler解析指令、插值表达式
  • 结构

    • $options
    • $el
    • $data
    • _proxyData()

    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、调用observe对象,监听数据的变化
            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
                    }
                })
            })
        }
    }
    
3、Observer

能够对数据对象的所有属性进行监听,如有变动可拿到最新值并通知Dep

  • 功能
    • 负责把data选项中的属性转换成响应式数据
    • data中的某个属性也是对象,把该属性转化成响应式数据
    • 数据变化发送通知
  • 结构
    • walk(data)
    • defineReactive(data, key, value)

observer.js

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) {
    
    
        //如果val是对象,会把对象也转化为响应数据
        this.walk(val)
        let that = this
        //负责收集依赖,并发送通知
        let dep = new Dep()

        Object.defineProperty(obj, key, {
    
    
            enumerable: true,
            configurable: true,
            get() {
    
    
                //直接return obj[key]会发生死循环
                // return obj[key]
                //收集依赖
                Dep.target && dep.addSub(Dep.target)
                return val 
            },
            set(newValue) {
    
    
                if (newValue === val) {
    
    
                    return
                }
                val = newValue
                //防止重新赋值以后,对象属性不是响应式的问题
                that.walk(val)
                //发送通知
                dep.notify()
            }
        })
    }

}
4、compiler
  • 功能
    • 负责编译模板,解析指令/差值表达式
    • 负责页面的首次渲染
    • 当数据变化后重新渲染视图
  • 结构
    • el
    • vm
    • compile(el)
    • compileElement(node)
    • complieText(node)

compile.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)
            }
            //判断node节点是否有子节点,如果有子节点,递归调用complie
            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 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])
            //创建watch对象,当数据改变时改变视图
            new Watcher(this.vm,key,newVlue => {
    
    
                console.log(newVlue,"======")
                node.textContent = newVlue
            })
        }
    }
    //判断元素属性是否是指令
    isDirective(attrName) {
    
    
        return attrName.startsWith('v-')
    }
    //判断节点是否是文本节点
    isTextNode(node) {
    
    
        return node.nodeType === 3
    }
    //判断节点是否是元素节点
    isElementNode(node) {
    
    
        return node.nodeType === 1
    }
}
5、Dep
  • 功能

    • 收集依赖,添加观察者(watcher)
    • 通知所有观察者
  • 结构

    subs:所有观察者

    addSub:添加观察者

    notify:通知观察者

dep.js

class Dep{
    
    
    constructor(){
    
    
        this.subs = []
    }

    //添加观察者
    addSub(sub){
    
    
        if(sub && sub.update){
    
    
            this.subs.push(sub)
        }
    }

    //发送通知
    notify(){
    
    
        this.subs.forEach(sub=>{
    
    
            sub.update()
        })
    }
}

6、watcher

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4HeR7kaH-1597762329056)(C:\Users\张艳杰\AppData\Roaming\Typora\typora-user-images\1596557521570.png)]

  • 功能
    • 当数据变化触发依赖,dep通知所有的watcher实例更新视图
    • 自身实例化的时候往dep对象中添加自己
  • 结构
    • vm
    • key(data中的属性名称)
    • cb(callback,回调函数)
    • oldValue
    • 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() {
    
    
        console.log("diaoyong")
        let newValue = this.vm[this.key]
        if (this.oldValue === newValue) {
    
    
            return
        }
        this.cb(newValue)
    }
    //创建
}

猜你喜欢

转载自blog.csdn.net/qiuqiu1628480502/article/details/108089707