vue 响应式原理模拟6 - 完整代码

56 阅读1分钟

回顾一下,整个建议的 vue 响应式代码中,首先在 vue.js 中存储了传入的参数,然后将 data 中数据都转换为 getter/setter 添加到了 vue 实例上。然后在 observer.js 中将 data 中的属性都转换为 getter/setter,如果属性是对象,则对象下的属性也都要转换成 getter/setter。处理完数据就要开始编译视图,我们遍历视图上所有的节点,将其分为两种类型,文本节点用插值表达式处理,元素节点用指令处理,完成渲染时将视图上用到 data 属性的地方都转换成对应的值。最后利用 dep.jswatcher.js 形成观察者模式,做到改变数据的时候同时改变视图。

index.html

<!DOCTYPE html>
<html>
<body>
  <div id="app">
    <div>差值表达式</div>
      <span>{{ msg }}</span>
      <span>{{ count }}</span>
    <div>v-text</div>
      <span v-text="msg"></span>
    <div>v-model</div>
      <input type="text" v-model="msg">
      <input type="text" v-model="count">
  </div>
  <script src="./dep.js"></script>
  <script src="./watcher.js"></script>
  <script src="./compiler.js"></script>
  <script src="./observer.js"></script>
  <script src="./vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        msg: 'test',
        count: 20,
        person: {name: 'zs'}
      }
    })
  </script>
</body>
</html>

vue.js

class Vue {
    constructor(options) {
        this.$options = options || {}
        this.$data = options.data || {}
        this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el 

        this._proxyData(this.$data)
        
        new Observer(this.$data)

        new Compiler(this)
    }

    _proxyData(data) {
        for (let key in data) {
            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 {
    constructor(data) {
        this.walk(data)
    }
    walk(data) {
        if (!data || typeof data !== 'object') return
        for(let key in data) {
            this.defineReactive(data, key)
        }
    }
    defineReactive(data, key) {
        let dep = new Dep()
        let value = data[key]
        this.walk(value)
        const self = this
        Object.defineProperty(data, key, {
            enumerable: true,
            configurable: true,
            get() {
                Dep.target && dep.addSub(Dep.target)
                return value
            },
            set(newValue) {
                if (newValue === value) return
                value = newValue
                self.walk(newValue)
                dep.notify()
            }
        })
    }
}

compiler.js

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

    compiler(el) {
        let childNodes = el.childNodes
        Array.from(childNodes).forEach(node => {
            if (this.isTextNode(node)) {
                this.compilerText(node)
            } else if (this.isElementNode(node)) {
                this.compilerElement(node)
            }
            if (node.childNodes && node.childNodes.length) {
                this.compiler(node)
            }
        })
    }

    compilerText(node) {
        // 文本节点替换插值表达式
        let value = node.textContent
        let reg = /\{\{(.+?)\}\}/
        let key = ''
        if (reg.test(value)) {
            value.replace(reg, (match, p1) => {
                key = p1.trim()
                node.textContent = this.vm[key]
            })
            new Watcher(this.vm, key, (newValue) => {
                node.textContent = newValue
            })
        }
    }
    compilerElement(node) {
        // 指令解析属性节点
        Array.from(node.attributes).forEach(attr => {
            let attrName = attr.name
            if (this.isDirective(attrName)) {
                let attrValue = attr.value
                this.update(node, attrName, attrValue)
            }
        })
    }
    // 用拼接指令名和 'Updater' 的方式为不同的指令操作方法命名
    update(node, attrName, key) {
        attrName = attrName.substr(2)
        let updateFn = this[attrName + 'Updater']
        updateFn && updateFn.call(this, node, this.vm[key], key)
    }
    textUpdater(node, value, key) {
        node.textContent = value
        new Watcher(this.vm, key, (newValue) => {
            node.textContent = newValue
        })
    }
    modelUpdater(node, value, key) {
        node.value = value
        new Watcher(this.vm, key, (newValue) => {
            node.value = newValue
        })
        // 双向绑定
        node.addEventListener('input', () => {
            this.vm[key] = node.value
        })
    }
    isTextNode(node) {
        return node.nodeType === 3
    }
    isElementNode(node) {
        return node.nodeType === 1
    }
    isDirective(attrName) {
        return attrName.startsWith('v-')
    }
}

dep.js

class Dep {
    constructor () {
        this.subs = []
    }
    // 收集依赖
    addSub (sub) {
        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
        this.key = key
        this.cb = cb
        Dep.target = this
        this.oldValue = vm[key]
        Dep.target = null
    }
    update() {
        let newValue = this.vm[this.key]
        if (newValue === this.oldValue) return
        this.cb(newValue)
    }
}