Vue2 响应式原理--简版实现

61 阅读1分钟

「这是我参与11月更文挑战的第18天,活动详情查看:2021最后一次更文挑战」。

Vue 响应式原理

Object.defineProperty

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

Object.defineProperty多个成员

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

proxy

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

发布者订阅者模式

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

观察者模式

<body>
  <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 dep = new Dep()
    let watcher = new Watcher()

    dep.addSub(watcher)

    dep.notify()
  </script>
</body>

Vue

  • 功能
  1. 负责接收初始化的参数(选项)
  2. 负责data中的属性注入到Vue实例,转换成getter/setter
  3. 负责调用observer监听data中所有属性的变化
  4. 负责调用compiler解析指令/插值表达式
  • 结构

    Vue

-----------------*

+$options

+$el

+$data

-----------------*

-_proxyData()

Observer

  • 功能
  1. 负责把data选项中的属性转换成响应式数据
  2. data中的某个属性也是对象,把该属性转化成响应式数据
  • 结构

    Observer

--------------------*

+walk(data)

+defineReactive(data,key,value)

Compiler

  • 功能
  1. 负责编译模板,解析指令/插值表达式
  2. 负责页面的首次渲染
  3. 当数据变化后重新渲染视图
  • 结构

Compiler

-------------------*

+el

+vm

-------------------*

+compile(el)

+compileElement(node)

+compileText(node)

+isDirective(attrName)

+isTextNode(node)

+isElementNode(node)

Dep(Dependency)

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

    Dep

---------------*

+subs

---------------*

+addSub(sub)

+notify()

Watcher

  • 功能
  1. 当数据变化触发依赖,dep通知所有的Watcher实例更新视图
  2. 自身实例化的时候往Dep对象中添加自己
  • 结构

    Watcher

-------------------*

+vm

+key

+cb

+oldValue

-------------------*

+update

<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/observer.js"></script>
    <script src="./js/compiler.js"></script>
    <script src="./js/vue.js"></script>
    <script>
        let vm = new Vue({
            el:"#app",
            data:{
                msg:"Hello Vue",
                count:100,
                person:{
                    name:"zs"
                }
            }
        })
        // vm.msg= {name: "ls"}
    </script>
</body>


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



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)
    }
}



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 ( data, key, val ) {
        let that = this
        // 负责收集依赖并发送通知
        let dep = new Dep()
        //如果val是对象,把val内部的属性转换成响应式数据
        this.walk(val)

        Object.defineProperty(data, key, {
            enumerable: true,
            configurable: true,
            get ( ) {
                // 收集依赖
                Dep.target && dep.addSub( Dep.target )
                return val
            },
            set ( newValue ) {
                 if ( newValue === val ) {
                     return
                 }

                 val = newValue
                 that.walk(newValue)
                //  发送通知 
                dep.notify() 
            }
        })
    }
}


class Compiler{
    constructor ( vm ) {
       this.el = vm.$el,
       this.vm = vm
       this.compile(this.el)
    }
    // 编译模板,处理文本节点和元素节点
    compile( el ) {
       let  childNodes = el.childNodes //el的子节点 是一个数组[]  el.children 代表是子元素 
       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 ) {
        //   遍历所有的属性节点  
        Array.from(node.attributes).forEach(attr => {
        //   判断是否是指令
            let attrName = attr.name
            if ( this.isDirective( attrName ) ) {
                attrName = attrName.substring(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 ) {
    //   console.dir(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
    }
}


 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
              }
          })
      })
    }
}