剖析手写Vue,你也可以手写一个MVVM框架

剖析手写Vue,你也可以手写一个MVVM框架#

邮箱:[email protected]
github: https://github.com/xiaoqiuxiong
作者:肖秋雄(eddy)
温馨提示:感谢阅读,笔者创作辛苦,如需转载请自觉注明出处哦

Vue MVVM响应式原理剖释

Vue是采用数据劫持配合发布者和订阅者模式,通过Object.definerProperty()来劫持各个属性的setter和setter,在数据变动时,发布消息给依赖收集器Dep,去通知观察者Watcher,触发对应的解释模板回调函数去更新视图。
详细点说就是MVVM作为绑定的入口,整合了Observer,Compile和Watcher三者,通过Observer来劫持且监听数据,通过Compile来解释编译模板指令,然后利用Watcher搭建Observer,Compile之间的联系,达到数据变化=>视图更新,视图交互变化=>数据变化=>视图更新双向绑定的效果。
示列:

手写Vue源码


inex.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>手写Vue</title>
</head>

<body>
    <div id="app">
        <h2>{{ person.name }} -- {{ person.age }}</h2>
        <h3>{{ person.favorite }}</h3>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <h3>{{ msg }}</h3>
        <div v-text='person.name'></div>
        <div v-text='msg'></div>
        <div v-html='htmlStr'></div>
        <input type="text" v-model='msg'>
        <button v-on:click="handlerClick">点击按钮</button>
        <br>
        <br>
        <div>
            数量: 
            <button v-on:click="sub">-</button>
            {{num}}
            <button v-on:click="add">+</button>
        </div>
    </div>
    <script src="./Observer.js"></script>
    <script src="./MVue.js"></script>
    <script>
        let vm = new MVue({
            el: '#app',
            data: {
                num: 1,
                person: {
                    name: '小马哥',
                    age: 18,
                    favorite: '喜欢大长腿妹妹!'
                },
                msg: '学习手写Vue框架',
                htmlStr: '<h3>我爱学习vue</h3>'
            },
            methods: {
                handlerClick() {
                    this.msg = '66'
                    this.person = {
                        name: '大马哥',
                        age: 99,
                        favorite: '喜欢大哥哥!'
                    }
                },
                add() {
                    this.num++
                },
                sub() {
                    if(this.num === 1) return
                    this.num = this.num -1
                }
            }
        })
    </script>

</html>

MVue.js


// 入口方法
class MVue {
    constructor(options) {
        this.$options = options
        this.$el = options.el
        this.$data = options.data

        if (this.$el) {
            // 1.实现一个数据观察者
            new Observer(this.$data)
            // 2.实现一个指令解释器
            new Compile(this.$el, this)
            // 代理this.$data => this
            this.proxyData(this.$data)
        }
    }

    // 代理
    proxyData(data) {
        for (const key in data) {
            Object.defineProperty(this, key, {
                get() {
                    return data[key]
                },
                set: newVal => {
                    data[key] = newVal
                }
            })
        }
    }
}

// 指令解释器 
class Compile {
    constructor(el, vm) {
        this.el = this.isElementNode(el) ? el : document.querySelector(el)
        this.vm = vm

        // 1.获取文档碎片对象,放入内存中可以减少页面回流和重绘
        const fragment = this.node2Fragment(this.el)
        // console.log(fragment);

        // 2.编译模板
        this.compile(fragment)

        // 3.追加子元素到根元素
        this.el.appendChild(fragment)
    }

    compile(fragment) {
        // 1.获取每一个子节点
        let childNodes = fragment.childNodes
        childNodes = this.convertToArray(childNodes)
        childNodes.forEach(child => {
            if (this.isElementNode(child)) {
                // console.log('元素节点', child);
                this.compileElement(child)
            } else {
                // console.log('文档节点', child);
                this.compileText(child)
            }
            if (child.childNodes && child.childNodes.length) {
                this.compile(child)
            }
        });
    }

    isDirective(name) {
        return name.startsWith('v-')
    }

    isElementNode(node) {
        // 判断是否是元素节点
        return node.nodeType === 1
    }

    convertToArray(nodes) {
        // 将childNodes返回的数据转化为数组的方法
        var array = null;
        try {
            array = Array.prototype.slice.call(nodes, 0);
        } catch (ex) {
            array = new Array();
            for (var i = 0, len = nodes.length; i < len; i++) {
                array.push(nodes[i]);
            }
        }
        return array;
    }

    compileElement(node) {
        // console.log(node);
        // <div v-text="msg"></div>
        const attributes = node.attributes
        // console.log(attributes);
        this.convertToArray(attributes).forEach(attr => {
            const { name, value } = attr
            // console.log(value);
            if (this.isDirective(name)) {
                // 是一个指令
                const [, dirctive] = name.split('-')
                const [dirName, eventName] = dirctive.split(':')
                //  console.log(dirName, eventName);
                // 更新数据 数据驱动视图
                compileUtil[dirName](node, value, this.vm, eventName)

                // 删除标签上的指令
                node.removeAttribute('v-' + dirctive)
            }
        })
    }

    compileText(node) {
        // 匹配双大括号 {{}}
        const content = node.textContent
        if (/\{\{(.+?)\}\}/.test(content)) {
            // console.log(content);
            compileUtil['text'](node, content, this.vm)
        }
    }

    node2Fragment(el) {
        // 创建文档碎片
        let f = document.createDocumentFragment()
        while (el.firstChild) {
            f.appendChild(el.firstChild)
        }
        return f
    }
}

const compileUtil = {
    text(node, expr, vm) {
        let value
        if (expr.indexOf('{{') !== -1) {
            value = expr.replace(/\{\{(.+?)\}\}/g, (...args) => {
                // 绑定观察者,将来数据发生变化,触发这里的回调函数去更是对应的视图
                new Watcher(vm, args[1], (newVal) => {
                    this.updater.textUpdater(node, this.getContentVal(expr, vm))
                })
                return this.getValue(args[1], vm)
            })
        } else {
            value = this.getValue(expr, vm)
            new Watcher(vm, expr, (newVal) => {
                this.updater.textUpdater(node, newVal)
            })
        }

        this.updater.textUpdater(node, value)
    },
    html(node, expr, vm) {
        let value = this.getValue(expr, vm)
        new Watcher(vm, expr, (newVal) => {
            this.updater.htmlUpdater(node, newVal)
        })
        this.updater.htmlUpdater(node, value)
    },
    model(node, expr, vm) {
        const value = this.getValue(expr, vm)
        // 绑定更新函数 数据=>视图
        new Watcher(vm, expr, (newVal) => {
            this.updater.modelUpdater(node, newVal)
        })
        // 视图=>数据=>视图
        node.addEventListener('input', e => {
            // 设置值
            this.setValue(expr, vm, e.target.value)
        })
        this.updater.modelUpdater(node, value)
    },
    on(node, expr, vm, eventName) {
        let fn = vm.$options.methods && vm.$options.methods[expr]
        node.addEventListener(eventName, fn.bind(vm), false)
    },
    getValue(expr, vm) {
        expr = expr.replace(/\s+/g, "")
        return expr.split('.').reduce((data, currentVal) => {
            // console.log(currentVal);
            return data[currentVal]
        }, vm.$data)
    },
    setValue(expr, vm, newVal) {
        expr = expr.replace(/\s+/g, "")
        return expr.split('.').reduce((data, currentVal) => {
            data[currentVal] = newVal
        }, vm.$data)
    },
    updater: {
        textUpdater(node, value) {
            node.textContent = value
        },
        htmlUpdater(node, value) {
            node.innerHTML = value
        },
        modelUpdater(node, value) {
            node.value = value
        }
    },
    getContentVal(expr, vm) {
        return expr.replace(/\{\{(.+?)\}\}/g, (...args) => {
            return this.getValue(args[1], vm)
        })
    }
}

Observer.js


class Watcher {
    constructor(vm, expr, cb) {
        this.vm = vm
        this.expr = expr
        this.cb = cb
        // 先把旧值保存起来
        this.oldVal = this.getOldVal()
    }

    getOldVal() {
        Dep.target = this
        const oldVal = compileUtil.getValue(this.expr, this.vm)
        Dep.target = null
        return oldVal
    }

    update() {
        const newVal = compileUtil.getValue(this.expr, this.vm)
        this.cb(newVal)
    }
}


class Dep {
    constructor() {
        // 定义观察者数组
        this.subs = []
    }

    // 收集观察者
    addSub(watcher) {
        this.subs.push(watcher)
    }

    // 通知观察者去更新视图
    notify() {
        // console.log('通知了观察者');
        this.subs.forEach(w => w.update())
    }
}


// 数据劫持监听
class Observer {
    constructor(data) {
        this.observer(data)
    }

    observer(data) {
        if (data && typeof data === 'object') {
            Object.keys(data).forEach(key => {
                this.defineReactive(data, key, data[key])
            })
        }
    }

    defineReactive(obj, key, value) {
        // 递归遍历,直到最后一个值不是对象
        this.observer(value)
        const dep = new Dep()
        Object.defineProperty(obj, key, {
            enumerable: true,
            configurable: false,
            get() {
                // 订阅数据变化时,往Dep中添加观察者
                Dep.target && dep.addSub(Dep.target)
                return value
            },
            set: (newVal) => {
                this.observer(newVal)
                // 重新更新值之前先对新值劫持监听
                value = newVal
                // 告诉Dep通知变化
                dep.notify()
            }
        })
    }
}


感谢阅读,笔者创作辛苦,如需转载请自觉注明出处哦

猜你喜欢

转载自www.cnblogs.com/it-xiong/p/12674893.html