前端技术 成长之路让前端飞程序员

vue 双向绑定实现

2019-04-11  本文已影响6人  寻找自我的兔茽

起因

用vue这么久,也了解过它的双向绑定原理,但是没有实现过,所以还是实地手写一个深入理解下。

它是什么

双向绑定,就是在单向绑定的基础上给可输入元素(input、textarea 等)添加了change( input )事件,来动态修改model。

总结: 双向绑定 = 单向绑定 + 事件的监听

原理分析

思考实现步骤

开始代码实现

<!DOCTYPE html>
<html>

    <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="practice">
            <h2>实现-vue-双向绑定</h2>

            <div v-text="name"></div>
            <div v-text="desc"></div>
            <input type="text" v-model="desc" />
        </div>

        <script src="./index.js"></script>
        <script>
            new Vue({
                el: '#practice',
                data: {
                    name: 'lingzi',
                    desc: 'i am so cute'
                }
            })
        </script>

    </body>

</html>

index.js

class Vue {
    constructor(options) {

    }
}
class Vue {

    constructor(options) {
        let data = options.data;
        const el = document.querySelector(options.el);

        this.Observer(data);
    }

    // 监听器
    Observer(obj) {
        if (!data || typeof data !== 'object') return;

        for (const key in obj) {
            let value = obj[key];
            Object.defineProperty(obj, key, {
                get: () => {
                    return value;
                },
                set: (newValue) => {
                    value = newValue;

                    // TODO 通知订阅者
                }
            })
        }
    }

}
  1. 实现一个订阅者Watcher,每一个Watcher都绑定一个更新函数,Watcher可以收到属性的变化通知,并执行相应的更新函数,从而更新视图。
class Vue {
    ... //省略
}

// 订阅者
class Watcher {

    constructor(el, vm, exp, attr) {
        this.el = el;
        this.vm = vm;
        this.exp = exp;
        this.attr = attr;

        this.update();
    }

    update() {
        this.el[this.attr] = this.vm.data[this.exp];   //更新视图
    }

}

3.因为订阅者是有很多个,所以我们需要有一个消息订阅器Dep来专门收集这些订阅者。

class Vue {
    ... //省略
     Observer(obj) {
        if (!obj || typeof obj !== 'object') return;

        for (const key in obj) {
            let value = obj[key];
            Object.defineProperty(obj, key, {
                get: () => {
                    return value;
                },
                set: (newValue) => {
                    value = newValue;

                    // TODO 通知订阅者
                    this.dep.notify();   // ++++++++加上这句
                }
            })
        }
    }
}

// 订阅者
class Watcher {
    ... //省略
}

// 收集订阅者
class Dep {
    constructor() {
        this.subs = [];
    }
    addSub(sub) {
        this.subs.push(sub);
    }
    notify() {
        this.subs.forEach((sub) => {
            sub.update();
        })
    }
}
  1. 实现一个解析器Compile,可以扫描解析每个节点的相关指令(v-model,v-on等)。如果节点存在这些指令,则初始化这些节点的模板数据,使之可以显示在视图上,然后初始化相应的订阅者(Watcher)。
class Vue {

    constructor(options) {
        ... //省略
        this.Observer(this.data);
        this.Compile(this.el);   // ++++++++++加上这句
    }

    // 监听器
    Observer(obj) {
        ... //省略
    }

    Compile(el) {
        const nodes = el.children;

        [...nodes].forEach((node, index) => {
            if (node.hasAttribute('v-text')) {
                let attrVal = node.getAttribute('v-text');
                this.dep.addSub(new Watcher(node, this, attrVal, 'innerHTML'));
            }

            if (node.hasAttribute('v-model')) {
                let attrVal = node.getAttribute('v-model');
                this.dep.addSub(new Watcher(node, this, attrVal, 'value'));
            }
        })

    }

}
  1. 事件监听,改变model数据
Compile(el) {
    const nodes = el.children;
    [...nodes].forEach((node, index) => {

        ... //省略

        if (node.hasAttribute('v-model')) {
            let attrVal = node.getAttribute('v-model');
            this.dep.addSub(new Watcher(node, this, attrVal, 'value'));

            // ++++++++++++ 加上下面两句
            node.addEventListener('input', () => {
                this.data[attrVal] = node.value;
            })
        }
    })
}

结尾发言

实现的简陋型,供自己理解。
代码仓库地址:https://github.com/lingziyb/study-notes/tree/master/vue-two-way-bind

上一篇 下一篇

猜你喜欢

热点阅读