Home > Web Front-end > Vue.js > In-depth discussion of the principle and implementation of two-way data binding in Vue

In-depth discussion of the principle and implementation of two-way data binding in Vue

青灯夜游
Release: 2022-08-10 17:55:44
forward
1589 people have browsed it

How to implement two-way data binding in Vue? The following article will take you to discuss the principle and implementation of two-way data binding in Vue. I hope it will be helpful to you!

In-depth discussion of the principle and implementation of two-way data binding in Vue

I have been using vue for a while. Although I have a general understanding of the principle of two-way binding, I have not explored its principle implementation, so this time I specially I spent a few nights reviewing information and reading relevant source code, and I also implemented a simple two-way binding version of vue. First, I will show the results to attract everyone:

In-depth discussion of the principle and implementation of two-way data binding in Vue

Effect Picture:

In-depth discussion of the principle and implementation of two-way data binding in Vue

Does it look similar to how vue is used? Next, let’s implement this SelfVue step by step from principle to implementation, from simple to difficult. Since this article is only for learning and sharing, it only briefly implements the principles without considering too many situations and designs. If you have any suggestions, please feel free to put them forward.

This article mainly introduces two major contents:

  • 1. The principle of two-way binding of vue data.

  • 2. The process of implementing a simple version of vue mainly implements the functions of {{}}, v-model and event instructions. (Learning video sharing: vue video tutorial)

Related code address: https://github.com/canfoo/self-vue

Vue data two-way binding principle


Vue data two-way binding is achieved through data hijacking combined with the publisher-subscriber model, then If Vue performs data hijacking, we can first take a look at what it means to output an object defined on Vue initialization data through the console.

Code:

var vm = new Vue({
    data: {
        obj: {
            a: 1
        }
    },
    created: function () {
        console.log(this.obj);
    }
});
Copy after login

Result:

In-depth discussion of the principle and implementation of two-way data binding in Vue

We can see that attribute a has two corresponding get and set methods, why Will there be these two more methods? Because vue implements data hijacking through Object.defineProperty().

What is Object.defineProperty() used for? It can control some unique operations of an object's attributes, such as read and write rights, and whether it can be enumerated. Here we will first study its two corresponding description attributes, get and set. If you are not familiar with its usage, Please click here to read more usage.

In normal times, we can easily print out the attribute data of an object:

var Book = {
  name: 'vue权威指南'
};
console.log(Book.name);  // vue权威指南
Copy after login

If you want to directly add the name of the book while executing console.log(book.name) A book title, how to deal with it? Or what should be used to monitor the property value of the object Book. At this time, Object.defineProperty() comes in handy. The code is as follows:

var Book = {}
var name = '';
Object.defineProperty(Book, 'name', {
  set: function (value) {
    name = value;
    console.log('你取了一个书名叫做' + value);
  },
  get: function () {
    return '《' + name + '》'
  }
})
 
Book.name = 'vue权威指南';  // 你取了一个书名叫做vue权威指南
console.log(Book.name);  // 《vue权威指南》
Copy after login

We set the name attribute of the object Book through Object.defineProperty() and rewrite its get and set operations. As the name suggests, get is a function triggered by reading the value of the name attribute, and set is a function triggered by setting the value of the name attribute, so when the statement Book.name = 'vue authoritative guide' is executed, the console will print out "You took it A book is called "The Authoritative Guide to Vue". Then, when this attribute is read, ""The Authoritative Guide to Vue"" will be output because we have processed the value in the get function. If we execute the following statement at this time, what will be output on the console?

console.log(Book);
Copy after login

Result:

In-depth discussion of the principle and implementation of two-way data binding in Vue

At first glance, it looks a bit similar to the vue data we printed above, indicating that vue does use this method. To carry out data hijacking. Next, we use its principle to implement a simple version of mvvm two-way binding code.

Idea Analysis


The implementation of mvvm mainly includes two aspects, data changes update the view, and view changes update the data:

In-depth discussion of the principle and implementation of two-way data binding in Vue

The key point is how the data updates the view, because the view updates the data through event monitoring. For example, the input tag can monitor the 'input' event. So we focus on analyzing how to update the view when the data changes.

数据更新视图的重点是如何知道数据变了,只要知道数据变了,那么接下去的事都好处理。如何知道数据变了,其实上文我们已经给出答案了,就是通过Object.defineProperty( )对属性设置一个set函数,当数据改变了就会来触发这个函数,所以我们只要将一些需要更新的方法放在这里面就可以实现data更新view了。

In-depth discussion of the principle and implementation of two-way data binding in Vue

思路有了,接下去就是实现过程了。

实现过程


我们已经知道实现数据的双向绑定,首先要对数据进行劫持监听,所以我们需要设置一个监听器Observer,用来监听所有属性。如果属性发上变化了,就需要告诉订阅者Watcher看是否需要更新。因为订阅者是有很多个,所以我们需要有一个消息订阅器Dep来专门收集这些订阅者,然后在监听器Observer和订阅者Watcher之间进行统一管理的。

接着,我们还需要有一个指令解析器Compile,对每个节点元素进行扫描和解析,将相关指令对应初始化成一个订阅者Watcher,并替换模板数据或者绑定相应的函数,此时当订阅者Watcher接收到相应属性的变化,就会执行对应的更新函数,从而更新视图。

因此接下去我们执行以下3个步骤,实现数据的双向绑定:

  • 1.实现一个监听器Observer,用来劫持并监听所有属性,如果有变动的,就通知订阅者。

  • 2.实现一个订阅者Watcher,可以收到属性的变化通知并执行相应的函数,从而更新视图。

  • 3.实现一个解析器Compile,可以扫描和解析每个节点的相关指令,并根据初始化模板数据以及初始化相应的订阅器。

流程图如下:

In-depth discussion of the principle and implementation of two-way data binding in Vue

1.实现一个Observer

Observer是一个数据监听器,其实现核心方法就是前文所说的Object.defineProperty( )。如果要对所有属性都进行监听的话,那么可以通过递归方法遍历所有属性值,并对其进行Object.defineProperty( )处理。如下代码,实现了一个Observer。

function defineReactive(data, key, val) {
    observe(val); // 递归遍历所有子属性
    Object.defineProperty(data, key, {
        enumerable: true,
        configurable: true,
        get: function() {
            return val;
        },
        set: function(newVal) {
            val = newVal;
            console.log('属性' + key + '已经被监听了,现在值为:“' + newVal.toString() + '”');
        }
    });
}
 
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 = 'vue权威指南'; // 属性name已经被监听了,现在值为:“vue权威指南”
library.book2 = '没有此书籍';  // 属性book2已经被监听了,现在值为:“没有此书籍”
Copy after login

思路分析中,需要创建一个可以容纳订阅者的消息订阅器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 + '已经被监听了,现在值为:“' + newVal.toString() + '”');
            dep.notify(); // 如果数据变化,通知所有订阅者
        }
    });
}
 
function Dep () {
    this.subs = [];
}
Dep.prototype = {
    addSub: function(sub) {
        this.subs.push(sub);
    },
    notify: function() {
        this.subs.forEach(function(sub) {
            sub.update();
        });
    }
};
Copy after login

从代码上看,我们将订阅器Dep添加一个订阅者设计在getter里面,这是为了让Watcher初始化进行触发,因此需要判断是否要添加订阅者,至于具体设计方案,下文会详细说明的。在setter函数里面,如果数据变化,就会去通知所有订阅者,订阅者们就会去执行对应的更新的函数。到此为止,一个比较完整Observer已经实现了,接下来我们开始设计Watcher。

2.实现Watcher

订阅者Watcher在初始化的时候需要将自己添加进订阅器Dep中,那该如何添加呢?我们已经知道监听器Observer是在get函数执行了添加订阅者Wather的操作的,所以我们只要在订阅者Watcher初始化的时候触发对应的get函数去执行添加订阅者操作即可,那要如何触发get的函数,再简单不过了,只要获取对应的属性值就可以触发了,核心原因就是因为我们使用了Object.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;
    }
};
Copy after login

这时候,我们需要对监听器Observer也做个稍微调整,主要是对应Watcher类原型上的get函数。需要调整地方在于defineReactive函数:

function defineReactive(data, key, val) {
    observe(val); // 递归遍历所有子属性
    var dep = new 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;
Copy after login

到此为止,简单版的Watcher设计完毕,这时候我们只要将Observer和Watcher关联起来,就可以实现一个简单的双向绑定数据了。因为这里没有还没有设计解析器Compile,所以对于模板数据我们都进行写死处理,假设模板上又一个节点,且id号为'name',并且双向绑定的绑定的变量也为'name',且是通过两个大双括号包起来(这里只是为了演示,暂时没什么用处),模板如下:

    <h1>{{name}}</h1>
Copy after login

这时候我们需要将Observer和Watcher关联起来:

function SelfVue (data, el, exp) {
    this.data = data;
    observe(data);
    el.innerHTML = this.data[exp];  // 初始化模板数据的值
    new Watcher(this, exp, function (value) {
        el.innerHTML = value;
    });
    return this;
}
Copy after login

然后在页面上new以下SelfVue类,就可以实现数据的双向绑定了:

    <h1>{{name}}</h1>

<script></script>
<script></script>
<script></script>
<script>
    var ele = document.querySelector(&#39;#name&#39;);
    var selfVue = new SelfVue({
        name: &#39;hello world&#39;
    }, ele, &#39;name&#39;);
 
    window.setTimeout(function () {
        console.log(&#39;name值改变了&#39;);
        selfVue.data.name = &#39;canfoo&#39;;
    }, 2000);
 
</script>
Copy after login

这时候打开页面,可以看到页面刚开始显示了是'hello world',过了2s后就变成'canfoo'了。到这里,总算大功告成一半了,但是还有一个细节问题,我们在赋值的时候是这样的形式 '  selfVue.data.name = 'canfoo'  ' 而我们理想的形式是'  selfVue.name = 'canfoo'  '为了实现这样的形式,我们需要在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;
            }
        });
    }
}
Copy after login

这下我们就可以直接通过'  selfVue.name = 'canfoo'  '的形式来进行改变模板数据了。如果想要迫切看到现象的童鞋赶快来获取代码

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;
}
Copy after login

接下来需要遍历各个节点,对含有相关指定的节点进行特殊处理,这里咱们先处理最简单的情况,只对带有 '{{变量}}' 这种形式的指令进行处理,先简道难嘛,后面再考虑更多指令情况:

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];
    updateText(node, initText);  // 将初始化的数据初始化到视图中
    new Watcher(this.vm, exp, function (value) {  // 生成订阅器并绑定更新函数
        self.updateText(node, value);
    });
},
function updateText (node, value) {
    node.textContent = typeof value == 'undefined' ? '' : value;
}
Copy after login

获取到最外层节点后,调用compileElement函数,对所有子节点进行判断,如果节点是文本节点且匹配{{}}这种形式指令的节点就开始进行编译处理,编译处理首先需要初始化视图数据,对应上面所说的步骤1,接下去需要生成一个并绑定更新函数的订阅器,对应上面所说的步骤2。这样就完成指令的解析、初始化、编译三个过程,一个解析器Compile也就可以正常的工作了。为了将解析器Compile与监听器Observer和订阅者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;
}
Copy after login

更改后,我们就不要像之前通过传入固定的元素值进行双向绑定了,可以随便命名各种变量进行双向绑定了:

    <div>
        <h2>{{title}}</h2>
        <h1>{{name}}</h1>
    </div>

<script></script>
<script></script>
<script></script>
<script></script>
<script>
 
    var selfVue = new SelfVue({
        el: &#39;#app&#39;,
        data: {
            title: &#39;hello world&#39;,
            name: &#39;&#39;
        }
    });
 
    window.setTimeout(function () {
        selfVue.title = &#39;你好&#39;;
    }, 2000);
 
    window.setTimeout(function () {
        selfVue.name = &#39;canfoo&#39;;
    }, 2500);
 
</script>
Copy after login

如上代码,在页面上可观察到,刚开始titile和name分别被初始化为 'hello world' 和空,2s后title被替换成 '你好' 3s后name被替换成 'canfoo' 了。废话不多说,再给你们来一个这个版本的代码(v2),获取代码

到这里,一个数据双向绑定功能已经基本完成了,接下去就是需要完善更多指令的解析编译,在哪里进行更多指令的处理呢?答案很明显,只要在上文说的compileElement函数加上对其他指令节点进行判断,然后遍历其所有属性,看是否有匹配的指令的属性,如果有的话,就对其进行解析编译。这里我们再添加一个v-model指令和事件指令的解析编译,对于这些节点我们使用函数compile进行解析处理:

function compile (node) {
    var nodeAttrs = node.attributes;
    var self = this;
    Array.prototype.forEach.call(nodeAttrs, function(attr) {
        var attrName = attr.name;
        if (self.isDirective(attrName)) {
            var exp = attr.value;
            var dir = attrName.substring(2);
            if (self.isEventDirective(dir)) {  // 事件指令
                self.compileEvent(node, self.vm, exp, dir);
            } else {  // v-model 指令
                self.compileModel(node, self.vm, exp, dir);
            }
            node.removeAttribute(attrName);
        }
    });
}
Copy after login

上面的compile函数是挂载Compile原型上的,它首先遍历所有节点属性,然后再判断属性是否是指令属性,如果是的话再区分是哪种指令,再进行相应的处理,处理方法相对来说比较简单,这里就不再列出来,想要马上看阅读代码的同学可以马上点击这里获取

最后我们在稍微改造下类SelfVue,使它更像vue的用法:

function SelfVue (options) {
    var self = this;
    this.data = options.data;
    this.methods = options.methods;
 
    Object.keys(this.data).forEach(function(key) {
        self.proxyKeys(key);
    });
 
    observe(this.data);
    new Compile(options.el, this);
    options.mounted.call(this); // 所有事情处理好后执行mounted函数
}
Copy after login

这时候我们可以来真正测试了,在页面上设置如下东西:

    <div>
        <h2>{{title}}</h2>
        <input>
        <h1>{{name}}</h1>
        <button>click me!</button>
    </div>

<script></script>
<script></script>
<script></script>
<script></script>
<script>
 
     new SelfVue({
        el: &#39;#app&#39;,
        data: {
            title: &#39;hello world&#39;,
            name: &#39;canfoo&#39;
        },
        methods: {
            clickMe: function () {
                this.title = &#39;hello world&#39;;
            }
        },
        mounted: function () {
            window.setTimeout(() => {
                this.title = &#39;你好&#39;;
            }, 1000);
        }
    });
 
</script>
Copy after login

是不是看起来跟vue的使用方法一样,哈,真正的大功告成!想要代码,直接点击这里获取!现象还没描述?直接上图!!!请观赏

In-depth discussion of the principle and implementation of two-way data binding in Vue

Actually, this rendering is the one posted at the beginning of this article. The previous article said that I will lead you to realize it, so I will post the image again here. This is called beginning and ending echo.

Original address: https://www.cnblogs.com/canfoo/p/6891868.html

(Learning video sharing: web front-end development, Basic Programming Video)

The above is the detailed content of In-depth discussion of the principle and implementation of two-way data binding in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template