vue数据双向绑定进修笔记。

什么是双向绑定

简朴说就是在数据和UI之间竖立双向的通讯通道,当用户经由历程Function转变了数据,那末这个转变也会马上反应到UI上;或许说用户经由历程UI的操纵也会随之引发对应的数据变动。
Vue是怎样完成双向数据绑定的?数据挟制?什么意思呢?太笼统了。与其说是数据挟制,更应该说是对象数据对象的setter和Getter完成挟制。然则Object.defineProperty仅仅是完成了对数据的监控,后续完成对UI的从新衬着并非它做的,所以这里还涉及到宣布-定阅情势;历程是,当监控的数据对象被变动后,这个变动会被播送给一切定阅该数据的watcher,然后由该watcher完成对页面的从新衬着。
步骤:

起首要对数据举行挟制,所以我们须要设置一个监听器Observer,用来监听一切的属性。
假如属性发生变化,就须要关照定阅者Watcher看是不是须要更新。
定阅者是有很多个,所以我们须要有一个音讯定阅器Dep来特地网络这些定阅者,然后在监听器Observer和定阅者Watcher之间举行统一管理的。
还须要一个指令剖析器Compile,对每一个节点元素举行扫描和剖析,将相干指令对应初始化成一个定阅者Watcher,并替代模板数据或许绑定响应的函数,此时当定阅者Watcher接收到响应属性的变化,就会实行响应的更新函数,从而更新视图。
1.完成一个监听器Observer,用来挟制并监听一切属性,假如有变动的,就关照定阅者。
2.完成一个定阅者Watcher,能够收到属性的变化关照并实行响应的函数,从而更新视图。
3.完成一个剖析器Compile,能够扫描和剖析每一个节点的相干指令,并依据初始化模板数据及初始化响应的定阅器。

流程图以下:
《vue数据双向绑定进修笔记。》

1.完成一个Observer

Observer是一个数据监听器,其完成中心要领就是Object.defineProperty().假如要对一切属性都举行监听的话,那末能够经由历程递归要领遍历一切属性值,并对其举行Object.defineProperty()处置惩罚。

function defineReactive(data,key.val){
    observe(val);//递归遍历一切子属性
    Obejct.defineProperty(data,key,{
        enumerable:true,
        configurable:true,
        get:function(){
            return val;
        },
        set:function(newVal){
            val = newVal;
            console.log('属性'+key+'已被监听了')
        }
    })
}
function observe(data){
    if(!data || typeof data !=='object'){
        return;
    }
    Object.keys(data).forEach(function(key){
        defineReactive(data,key,data[key])
    })
}
var library={
    book1:{
        name:''
    },
    book2:''
}
observe(library);
library.book1.name='123';
library.book2='456'

思绪剖析中,须要建立一个能够包容定阅者的音讯定阅器Dep,定阅器Dep重要担任网络定阅者,然后再属性变化的时刻实行对应定阅者的更新函数。所以明显定阅者须要有一个容器,这个容器就是list,将上面的Observer轻微革新下,植入音讯定阅者:

function defineReactive(data,key,val){
    observe(val)//递归遍历一切子属性
    var dep = new Dep();
    Object.defineProperty(data,key,{
        enumerable:true,
        configurable:true,
        get:function(){
            if(是不是须要增加定阅者){
                dep.addSub(watcher);//在这里增加一个定阅者
            }
            return val;
        },
        set:function(newVal){
            if(val === newVal){
                return;
            }
            val = newVal;
            console.log('属性'+key+'已被监听了');
            dep.notify();//假如数据变化,关照定阅者
        }
    })
}
function Dep(){
    this.subs = [];
}
Dep.prototype={
    addSub:function(sub){
        this.subs.push(sub);
    },
    notify:function(){
        this.subs.forEach(function(sub){
            sub.update();
        })
    }
}

从代码上看,我们将定阅器Dep增加一个定阅者设想在getter内里,这是为了让Watcher初始化举行触发,因而须要推断是不是须要增加定阅者。在setter函数内里,假如数据变化,就会去关照一切定阅者,定阅者们就会去实行对应的更新函数。到此,一个比较完全的Obsever已完成了,接下来我们最先设想Watcher。

完成Watcher

定阅者Watcher在初始化的时刻须要将本身增加进定阅器Dep中,那该怎样增加呢?我们已晓得监听器Observer是在get函数实行了增加定阅者Watcher的操纵的,所以我们只需在定阅者Watcher初始化的时刻触发对应的get函数去实行增加定阅者操纵即可,那要怎样触发get的函数呢?只需猎取对应的属性值就能够触发了,缘由就是我们运用了Obejct.defineProperty()举行数据监听。这里另有一个细节点须要处置惩罚,我们只需在定阅者Watcher初始化的时刻才须要增加定阅者,所以须要做一个推断操纵,因而能够在定阅器上做一下四肢:在Dep.target上缓存下定阅者,增加胜利后再将其去掉就能够了。定阅者Watcher的完成以下:

function Watcher(vm,exp,cb){
    this.cb = cb;
    this.vm = vm;
    this.exp = exp;
    this.value = this.get();//将本身增加到定阅器的操纵
}
Watcher.prototype={
    update:function(){
        this.run();
    },
    run:function(){
        var value = this.vm.data[this.exp];
        var oldVal = this.value;
        if(value!==oldVal){
            this.value = value;
            this.cb.call(this.vm,value,oldVal)
        }
    },
    get:function(){
        Dep.target = this;//缓存本身
        var value = this.vm.data[this.exp]//强行实行监听器里的get函数
        Dep.target = null;//开释本身
        return value;
    }
}

到此为止,简朴版的Watcher设想终了,这时刻我们须要将Observer和Watcher关联起来,就能够完成一个简朴的双向数据绑定了。
简朴的例子:

<!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>Document</title>
</head>
<body>
  <h1 id="name">{{name}}</h1>
</body>
<script> 
function observe(data) {
    if (!data || typeof data !== 'object') {
        return;
    }
    Object.keys(data).forEach(function(key) {
        defineReactive(data, key, data[key]);
    });
};
function Dep () {
    this.subs = [];
}
Dep.prototype = {
    addSub: function(sub) {
        this.subs.push(sub);
    },
    notify: function() {
        this.subs.forEach(function(sub) {
            sub.update();
        });
    }
};
function Watcher(vm, exp, cb) {
    this.cb = cb;
    this.vm = vm;
    this.exp = exp;
    this.value = this.get();  // 将本身增加到定阅器的操纵
}
Watcher.prototype = {
    update: function() {
        var value = this.vm.data[this.exp];
        var oldVal = this.value;
        if (value !== oldVal) {
            this.value = value;
            this.cb.call(this.vm, value, oldVal);
        }
    },
    get: function() {
        Dep.target = this;  // 缓存本身
        var value = this.vm.data[this.exp]  // 强制实行监听器里的get函数
        Dep.target = null;  // 开释本身
        return value;
    }
};
function defineReactive(data, key, val) {
    observe(val); // 递归遍历一切子属性
    var dep = new Dep(); 
    console.log(dep)
    Object.defineProperty(data, key, {
        enumerable: true,
        configurable: true,
        get: function() {
            if (Dep.target) { // 推断是不是须要增加定阅者
                dep.addSub(Dep.target); // 在这里增加一个定阅者
            }
            return val;
        },
        set: function(newVal) {
            if (val === newVal) {
                return;
            }
            val = newVal;
            console.log('属性' + key + '已被监听了,如今值为:“' + newVal.toString() + '”');
            dep.notify(); // 假如数据变化,关照一切定阅者
        }
    });
}
Dep.target = null;
//在new SelfVue做一个代办,让接见selfVue的属性代办为接见selfVue.data的属性,完成道理照样运用Object.defineProperty()对属性值再包一层。
function SelfVue (data, el, exp) {
    var self = this;
    this.data = data;
    Object.keys(data).forEach(function(key) {
        self.proxyKeys(key);  // 绑定代办属性
    });
    observe(data);
    el.innerHTML = this.data[exp];  // 初始化模板数据的值
    new Watcher(this, exp, function (value) {
        el.innerHTML = value;
    });
    return this;
}

SelfVue.prototype = {
    proxyKeys: function (key) {
        var self = this;
        Object.defineProperty(this, key, {
            enumerable: false,
            configurable: true,
            get: function proxyGetter() {
                return self.data[key];
            },
            set: function proxySetter(newVal) { 
                self.data[key] = newVal;
            }
        });
    }
}
var ele = document.querySelector('#name');
var selfVue = new SelfVue({
    name: 'hello world'
}, ele, 'name');
window.setTimeout(function () {
    console.log('name值转变了');
    selfVue.name = 'canfoo';
}, 2000);

</script>
</html>

3.完成Compile

虽然上面已完成了一个双向数据绑定的例子,然则全部历程都没有去剖析dom节点,而是直接牢固某个节点举行替代数据的,所以接下来须要完成一个剖析器Compile来做剖析和绑定事情。剖析器Compile完成步骤:
1.剖析模板指令,并替代模板数据,初始化视图。
2.将模板指令对应的节点绑定对应的更新函数,初始化响应的定阅器
为了剖析模板,起首须要猎取dom元素,然后对含有dom元素上含有指令的节点举行处置惩罚,因而这个环节须要对dom操纵比较频仍,所以能够先建一个fragment片断,将须要剖析的dom节点存入fragment片断里再举行处置惩罚:

function nodeToFragment(el){
    var fragment = document.createDocumentFragment();
    var child = el.firstChild;
    while(child){
        //将Dom元素移入fragment中
        fragment.appendChild(child);
        child = el.firstChild
    }
    return fragment;
}

接下来须要遍历各个节点,对含有相干指定的节点举行特别处置惩罚,这里先处置惩罚最简朴的状况,只对带有{{变量}}这类情势的指令举行处置惩罚。

function compileElement(el){
    var childNodes = el.childNodes;
    var self = this;
    [].slice.call(childNodes).forEach(function(node){
        var reg = /\{\(.*)\}\}/;
        var text = node.textContent;
        if(self.isTextNode(node)&&reg.test(text)){
            self.compileText(node,reg.exec(text)[1])
        }
        if(node.childNodes&&node.childNodes.length){
            self.compileElement(node);//继承递归遍历子节点。
        }
    })
}
function compileText(node,exp){
    var self = this;
    var initText = this.vm[exp];
    this.updateText(node,initText);
    new Watcher(this.vm,exp,function(value){
        self.updateText(node,value);
    })
}
function (node,value){
    node.tetxContent = typeof value =='undefined'?'':value;
}

猎取到最外层节点后,挪用compileElement函数,对一切子节点举行推断,假如节点是文本节点且婚配{{}}这类情势指令的节点就最先举行变异处置惩罚,编译处置惩罚起首须要初始化视图数据,对应上面所说的步骤1,接下来须要天生一个并绑定更新函数的定阅器,对应上面所说的步骤2.如许就完成指令的剖析、初始化、编译三个历程,一个剖析器Compile也就能够一般的事情了。为了将剖析器Compile与监听器Obsever和定阅者Watcher关联起来,我们须要再修正一下类SelfVue函数:

function SelfVue(options){
    var self = this;
    this.vm = this;
    this.data = options;
    Object.keys(this.data).forEach(function(key){
        self.proxyKeys(key);
    })
    observe(this.data);
    new Compile(options,this.vm);
    return this;
}

createDocumentFragment:
建立一个新的空缺的文档片断。
语法:

let fragment = document.createDocumentFragment();

fragment是一个指向空DocumentFragment对象的援用。DocumentFragment是DOM节点。它们不是主dom数的一部分。一般的用例是建立文档片断,将元素附加到文档片断,然后将文档片断附加到DOM树。在DOM树中,文档片断被其一切的子元素所替代。
由于文档片断存在于内存中,并不在DOM树中,所以将子元素插进去到文档片断时不会引发页面回流。因而运用文档片断一般会带来更好的机能。

<!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>Document</title>
</head>
<body>
  <div id="app">
    <h2>{{title}}</h2>
    <h1>{{name}}</h1>
  </div>
</body>
<script> 

function Observer(data) {
    this.data = data;
    this.walk(data);
}
Observer.prototype = {
    walk: function(data) {
        var self = this;
        Object.keys(data).forEach(function(key) {
            self.defineReactive(data, key, data[key]);
        });
    },
    defineReactive: function(data, key, val) {
        var dep = new Dep();
        var childObj = observe(val);
        Object.defineProperty(data, key, {
            enumerable: true,
            configurable: true,
            get: function() {
                console.log(6)
                if (Dep.target) {
                    dep.addSub(Dep.target);
                }
                return val;
            },
            set: function(newVal) {
                console.log(5)
                if (newVal === val) {
                    return;
                }
                val = newVal;
                dep.notify();
            }
        });
    }
};
function observe(value, vm) {
    if (!value || typeof value !== 'object') {
        return;
    }
    return new Observer(value);
};
function Dep () {
    this.subs = [];
}
Dep.prototype = {
    addSub: function(sub) {
        this.subs.push(sub);
    },
    notify: function() {
        this.subs.forEach(function(sub) {
            sub.update();
        });
    }
};
Dep.target = null;
function Watcher(vm, exp, cb) {
    this.cb = cb;
    this.vm = vm;
    this.exp = exp;
    this.value = this.get();  // 将本身增加到定阅器的操纵
}
Watcher.prototype = {
    update: function() {
        this.run();
    },
    run: function() {
        var value = this.vm.data[this.exp];
        var oldVal = this.value;
        if (value !== oldVal) {
            this.value = value;
            this.cb.call(this.vm, value, oldVal);
        }
    },
    get: function() {
        console.log(4)
        Dep.target = this;  // 缓存本身
        var value = this.vm.data[this.exp]  // 强制实行监听器里的get函数
        Dep.target = null;  // 开释本身
        return value;
    }
};
function SelfVue (options) {
    var self = this;
    this.vm = this;
    this.data = options.data;
    Object.keys(this.data).forEach(function(key) {
        self.proxyKeys(key);
    });
    observe(this.data);
    new Compile(options.el, this.vm);
    return this;
}
SelfVue.prototype = {
    proxyKeys: function (key) {
        var self = this;
        Object.defineProperty(this, key, {
            enumerable: false,
            configurable: true,
            get: function proxyGetter() {
                return self.data[key];
            },
            set: function proxySetter(newVal) {
                self.data[key] = newVal;
            }
        });
    }
}
function Compile(el, vm) {
    this.vm = vm;
    this.el = document.querySelector(el);
    this.fragment = null;
    this.init();
}
Compile.prototype = {
    init: function () {
        if (this.el) {
            this.fragment = this.nodeToFragment(this.el);
            this.compileElement(this.fragment);
            this.el.appendChild(this.fragment);
        } else {
            console.log('Dom元素不存在');
        }
    },
    nodeToFragment: function (el) {
        var fragment = document.createDocumentFragment();
        var child = el.firstChild;
        while (child) {
            // 将Dom元素移入fragment中
            fragment.appendChild(child);
            child = el.firstChild
        }
        return fragment;
    },
    compileElement: function (el) {
        var childNodes = el.childNodes;
        var self = this;
        [].slice.call(childNodes).forEach(function(node) {
            var reg = /\{\{(.*)\}\}/;
            var text = node.textContent;
            if (self.isTextNode(node) && reg.test(text)) {  // 推断是不是是相符这类情势{{}}的指令
                self.compileText(node, reg.exec(text)[1]);
            }
            if (node.childNodes && node.childNodes.length) {
                self.compileElement(node);  // 继承递归遍历子节点
            }
        });
    },
    compileText: function(node, exp) {
        console.log(1)
        var self = this;
        var initText = this.vm[exp];
        this.updateText(node, initText);  // 将初始化的数据初始化到视图中
        new Watcher(this.vm, exp, function (value) { // 天生定阅器并绑定更新函数
            self.updateText(node, value);
        });
    },
    updateText: function (node, value) {
        console.log(2)
        node.textContent = typeof value == 'undefined' ? '' : value;
    },
    isTextNode: function(node) {
        return node.nodeType == 3;
    }
}
var selfVue = new SelfVue({
    el: '#app',
    data: {
        title: 'hello world',
        name: '13'
    }
});
// window.setTimeout(function () {
//     selfVue.title = '你好';
// }, 2000);
 
// window.setTimeout(function () {
//     selfVue.name = 'canfoo';
// }, 2500);

</script>
</html>
<script>
</script>

代码剖析:

1.new SelfVue() 做了三件事:1.运用Object.definePrototype代办让接见selfVue的属性代办为接见selfVue.data的属性。2.一样运用Object.definePrototype数据挟制。3.new Compile()。
    原文作者:Lessong
    原文地址: https://segmentfault.com/a/1190000018663673
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞