Home  >  Article  >  Web Front-end  >  A brief discussion on the principle and implementation method of two-way binding in Vue.js

A brief discussion on the principle and implementation method of two-way binding in Vue.js

青灯夜游
青灯夜游forward
2020-10-27 17:48:492557browse

A brief discussion on the principle and implementation method of two-way binding in Vue.js

#One of the most unique features of Vue is its non-intrusive reactive system. Data models are just ordinary JavaScript objects. And when you modify them, the view updates. Vue is implemented through two-way binding. This article will introduce the principle and implementation method of Vue two-way binding.

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.

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. We can first take a look at what it means to output an object defined on the vue initialization data through the console.

Code:

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

Result:

A brief discussion on the principle and implementation method of two-way binding in Vue.js

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 mainly study its two corresponding description attributes, get and set.

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

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

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权威指南》

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 named a book called vue authoritative guide". Then, when reading this attribute, "Vue Authoritative Guide" 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?

A brief discussion on the principle and implementation method of two-way binding in Vue.js

At first glance, it looks a bit similar to the vue data we printed above, indicating that vue does use this method to hijack data. 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:

A brief discussion on the principle and implementation method of two-way binding in Vue.js

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.

The focus of the data update view is how to know that the data has changed. As long as you know that the data has changed, the next thing will be easy to handle. How to know that the data has changed? In fact, we have already given the answer above, which is to set a set function on the property through Object.defineProperty().

This function will be triggered when the data changes, so we only need to put some methods that need to be updated here to update the data view.

A brief discussion on the principle and implementation method of two-way binding in Vue.js

Now that we have the idea, the next step is the implementation process.

Implementation process

We already know that to implement two-way binding of data, we must first hijack and monitor the data, so we need to set up a monitor Observer is used to monitor all properties. If the attribute changes, you need to tell the subscriber Watcher to see if it needs to be updated.

Because there are many subscribers, we need to have a message subscriber Dep to specifically collect these subscribers, and then manage them uniformly between the listener Observer and the subscriber Watcher.

Next, we also need an instruction parser, Compile, to scan and parse each node element, initialize the relevant instructions into a subscriber Watcher, and replace the template data or bind the corresponding function.

此时当订阅者Watcher接收到相应属性的变化,就会执行对应的更新函数,从而更新视图。因此接下去我们执行以下3个步骤,实现数据的双向绑定:

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

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

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

流程图如下:

A brief discussion on the principle and implementation method of two-way binding in Vue.js

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已经被监听了,现在值为:“没有此书籍”

思路分析中,需要创建一个可以容纳订阅者的消息订阅器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();
        });
    }
};

从代码上看,我们将订阅器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;
    }
};

这时候,我们需要对监听器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;

到此为止,简单版的Watcher设计完毕,这时候我们只要将Observer和Watcher关联起来,就可以实现一个简单的双向绑定数据了。

因为这里没有还没有设计解析器Compile,所以对于模板数据我们都进行写死处理,假设模板上又一个节点,且id号为'name',并且双向绑定的绑定的变量也为'name',且是通过两个大双括号包起来。

模板如下:

<body>
    <h1 id="name">{{name}}</h1>
</body>

这时候我们需要将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;
}

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

<body>
    <h1 id="name">{{name}}</h1>
</body>



这时候打开页面,可以看到页面刚开始显示了是'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;
            }
        });
    }
}

这下我们就可以直接通过'  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;
}

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

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 == &#39;undefined&#39; ? &#39;&#39; : value;
}

获取到最外层节点后,调用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;
}

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

<body>
    <div id="app">
        <h2>{{title}}</h2>
        <h1>{{name}}</h1>
    </div>
</body>
<script src="js/observer.js"></script>
<script src="js/watcher.js"></script>
<script src="js/compile.js"></script>
<script src="js/index.js"></script>
<script type="text/javascript">
 
    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>

如上代码,在页面上可观察到,刚开始titile和name分别被初始化为 'hello world' 和空,2s后title被替换成 '你好' 3s后name被替换成 'canfoo' 了。

到这里,一个数据双向绑定功能已经基本完成了,接下去就是需要完善更多指令的解析编译,在哪里进行更多指令的处理呢?

答案很明显,只要在上文说的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);
        }
    });
}

上面的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函数
}

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

<body>
    <div id="app">
        <h2>{{title}}</h2>
        <input v-model="name">
        <h1>{{name}}</h1>
        <button v-on:click="clickMe">click me!</button>
    </div>
</body>
<script src="js/observer.js"></script>
<script src="js/watcher.js"></script>
<script src="js/compile.js"></script>
<script src="js/index.js"></script>
<script type="text/javascript">
 
     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>

实现效果:

A brief discussion on the principle and implementation method of two-way binding in Vue.js

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

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

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete