vue.js --- 响应式原理模拟实现

439

Vue 响应式原理模拟实现

1)整体分析

  • Vue 基本结构
  • 打印 Vue 实例观察
  • 整体结构

  • Vue
    • 把 data 中的成员注入到 Vue 实例,并且把 data 中的成员转成 getter/setter
  • Observer
    • 能够对数据对象的所有属性进行监听,如有变动可拿到最新值并通知 Dep

2)Vue

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

  • 代码
// 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
                }
            })
        })
    }
}

3) Observer

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

  • 代码
// 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])
        })
    }

    // 调用 Object.defineProperty 把属性转换成 getter/setter
    defineReactive (obj, key, val) { // obj--data数据对象,key--data中属性,val--data[key]的值
        // 记录此时的 this
        const that = this

        // 负责收集依赖,并发送通知
        let dep = new Dep()

        // 如果 obj 中某个属性(val)也是一个对象,把 val 内部的属性也转换成响应式数据
        this.walk(val)

        Object.defineProperty(obj, key, {
            enumerable: true,
            configurable: true,
            get () {
                // 收集依赖
                Dep.target && dep.addSub(Dep.target)
                
                return val
            },
            set (newValue) {
                if(newValue === val) {
                    return
                }
                val = newValue
                // 如果 newValue 是一个对象,把赋值后的 newValue 部的属性也转换成响应式数据
                that.walk(newValue)

                // 发送通知
                dep.notify()
            }
        })
    }

}

4) Compiler

  • 功能

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

  • 代码

// compiler.js
class Compiler {
    constructor (vm) {
        this.el = vm.$el
        this.vm = vm
        this.compile(this.el)
    }

    // 编译模板,处理文本节点和元素节点
    compile (el) {
        const childNodes = [...el.childNodes]
        // let childNodes = Array.from(el.childNodes)
        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(Array.from(node.attributes))
        // 遍历所有的属性节点
        Array.from(node.attributes).forEach(attr =>{
            console.log(attr)
            // 判断是否是指令
            let attrName = attr.name
            // console.log("Compiler -> compileElement -> attrName", attrName)
            if (this.isDirective(attrName)) {
                // v-text --> text
                attrName = attrName.substr(2)  //v-text
                let key = attr.value //如 <div v-text="msg"></div> 中的 msg
                // console.log("Compiler -> compileElement -> key", key)
                this.update(node, key, attrName)
            }
        })
    }

    // 不同指令所调用的函数
    update (node, key, attrName) {
        let updateFn = this[attrName + 'Updater'];
        updateFn && updateFn.call(this, node, this.vm[key], key) // 此处的 this 就是 compiler 对象
    }

    // 处理 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)
        // {{ msg }}
        const reg = /\{\{(.+?)\}\}/
        const 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
    }
}

5) Dep

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

  • 代码
// 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

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

  • 代码
// 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 (在observer类中实现)

        // 更新前的值
        this.oldValue = vm[key]

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

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

7) 调试

  • 调试页面首次渲染的过程
  • 调试数据改变更新视图的过程

8)总结

  • 给属性重新赋值成对象,是否是响应式的? ------
  • 给 Vue 实例 新增一个成员,是否是响应式的?------
  • 流程图