search
HomeWeb Front-endJS TutorialHow to understand the principle of two-way binding of Vue data

How to understand the principle of two-way binding of Vue data

Apr 25, 2019 pm 12:00 PM
vueData two-way binding

The principle of two-way binding of Vue data is achieved through data hijacking combined with the "publisher-subscriber" model. First, the data is monitored, and then the subscriber is notified when the monitored properties change. Whether to update, if updated, the corresponding update function will be executed to update the view.

How to understand the principle of two-way binding of Vue data

The two-way data binding principle of Vue is achieved through data hijacking combined with the publisher-subscriber model. First, the data is monitored, and then when When the monitored properties change, the subscriber is told whether to update. If updated, the corresponding update function will be executed to update the view

How to understand the principle of two-way binding of Vue data

[Recommended course: Vue tutorial

MVC mode

The previous MVC mode was one-way binding, that is, the Model was bound to the View. When we update the Model with JavaScript code, the View will automatically update

How to understand the principle of two-way binding of Vue data

MVVM mode

MVVM mode is Model–View– ViewModel mode. It realizes that changes in View are automatically reflected in ViewModel and vice versa. The understanding of two-way binding is that when the user updates the View, the Model's data is automatically updated. This situation is two-way binding. To be more detailed, on the basis of one-way binding, a change (input) event is added to the input elements input, textare, etc. (the change event is triggered, and the status of the View is updated) to dynamically modify the model.

How to understand the principle of two-way binding of Vue data

Two-way binding principle

Vue data two-way binding is achieved through data hijacking combined with the publisher-subscriber model. Implementation

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 listener Observer 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 a message subscriber Dep to specifically collect these subscribers, and then manage them uniformly between the Observer and the Watcher. Next, we also need an instruction parser Compile to scan and parse each node element, initialize the relevant instructions (such as v-model, v-on) into a subscriber Watcher, and replace the template data or bind it Corresponding function, when the subscriber Watcher receives the change of the corresponding attribute, it will execute the corresponding update function to update the view.

So next we perform the following three steps to achieve two-way binding of data:

(1) Implement a listener Observer to hijack and monitor all properties. If there are changes , notify subscribers.

(2) Implement a subscriber Watcher. Each Watcher is bound to an update function. The watcher can receive notification of attribute changes and execute the corresponding function to update the view.

(3) Implement a parser Compile that can scan and parse the relevant instructions of each node (v-model, v-on and other instructions). If the node has v-model, v-on and other instructions, The parser Compile initializes the template data of this type of node so that it can be displayed on the view, and then initializes the corresponding subscriber (Watcher).

How to understand the principle of two-way binding of Vue data

Implementing an Observer

Observer is a data listener, and its core implementation method is Object.defineProperty(). If you want to monitor all properties, you can traverse all property values ​​​​through recursion and process them with Object.defineProperty()
The following code implements an Observer.

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 getter () {                
        if (Dep.target) {                  
        // 在这里添加一个订阅者
                  console.log(Dep.target)
                    dep.addSub(Dep.target);
                }                return val;
            },           
            // setter,如果对一个对象属性值改变,就会触发setter中的dep.notify(),
            通知watcher(订阅者)数据变更,执行对应订阅者的更新函数,来更新视图。
            set: function setter (newVal) {                
            if (newVal === val) {                    
            return;
                }
                val = newVal;              
                // 新的值是object的话,进行监听
                childObj = observe(newVal);
                dep.notify();
            }
        });
    }
};function observe(value, vm) {    if (!value || typeof value !== 'object') {        
return;
    }    return new Observer(value);
};// 消息订阅器Dep,订阅器Dep主要负责收集订阅者,然后在属性变化的时候执行对应订阅者的更新函数
function Dep () {    
this.subs = [];
}
Dep.prototype = {  /**
   * [订阅器添加订阅者]
   * @param  {[Watcher]} sub [订阅者]
   */
    addSub: function(sub) {        
    this.subs.push(sub);
    },  // 通知订阅者数据变更
    notify: function() {        
    this.subs.forEach(function(sub) {
            sub.update();
        });
    }
};
Dep.target = null;

In Observer, when I looked at other people’s source code, one thing I didn’t understand was where Dep.target came from. I believe some people will have the same problem as me. question. Don't worry here. When you write about Watcher, you will find that Dep.target comes from Watcher.

Implementing a Watcher

Watcher is a subscriber. Used to process the update message sent by the Observer and execute the update function bound to the Watcher.

The following code implements a 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;
    }
};

In the process of studying the code, I think the most complicated thing is to understand the parameters of these functions. Later, after I output these parameters, the functions These functions are also easy to understand. vm is the SelfValue object to be written later, which is equivalent to an object of new Vue in Vue. exp is the attribute value of the node node's v-model or v-on:click and other instructions.

As can be seen from the above code, in the getter function of Watcher, Dep.target points to itself, which is the Watcher object. In the getter function,

var value = this.vm.data[this.exp]  // 强制执行监听器里的get函数。
这里获取vm.data[this.exp] 时,会调用Observer中Object.defineProperty中的get函数
get: function getter () {                
if (Dep.target) {                  
// 在这里添加一个订阅者                  
console.log(Dep.target)                    
dep.addSub(Dep.target);                
}                
return val;            
},

thus adds the watcher to the subscriber, which solves the problem of where the above Dep.target comes from.

Implement a Compile

Compile主要的作用是把new SelfVue 绑定的dom节点,(也就是el标签绑定的id)遍历该节点的所有子节点,找出其中所有的v-指令和" {{}} ".
(1)如果子节点含有v-指令,即是元素节点,则对这个元素添加监听事件。(如果是v-on,则node.addEventListener('click'),如果是v-model,则node.addEventListener('input'))。接着初始化模板元素,创建一个Watcher绑定这个元素节点。

(2)如果子节点是文本节点,即" {{ data }} ",则用正则表达式取出" {{ data }} "中的data,然后var initText = this.vm[exp],用initText去替代其中的data。

实现一个MVVM

可以说MVVM是Observer,Compile以及Watcher的“boss”了,他需要安排给Observer,Compile以及Watche做的事情如下

(1)Observer实现对MVVM自身model数据劫持,监听数据的属性变更,并在变动时进行notify
(2)Compile实现指令解析,初始化视图,并订阅数据变化,绑定好更新函数
(3)Watcher一方面接收Observer通过dep传递过来的数据变化,一方面通知Compile进行view update。
最后,把这个MVVM抽象出来,就是vue中Vue的构造函数了,可以构造出一个vue实例。

最后写一个html测试一下我们的功能

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>self-vue</title></head><style>
    #app {        
    text-align: center;
    }</style><body>
    <div id="app">
        <h2 id="title">{{title}}</h2>
        <input v-model="name">
        <h1 id="name">{{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/mvvm.js"></script>
    <script type="text/javascript">
     var app = 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></html>

先执行mvvm中的new SelfVue(...),在mvvm.js中,

observe(this.data);
new Compile(options.el, this);

先初始化一个监听器Observer,用于监听该对象data属性的值。
然后初始化一个解析器Compile,绑定这个节点,并解析其中的v-," {{}} "指令,(每一个指令对应一个Watcher)并初始化模板数据以及初始化相应的订阅者,并把订阅者添加到订阅器中(Dep)。这样就实现双向绑定了。
如果v-model绑定的元素,

<input v-model="name">

即输入框的值发生变化,就会触发Compile中的

node.addEventListener(&#39;input&#39;, function(e) {            
var newValue = e.target.value;            
if (val === newValue) {                
return;
            }            
            self.vm[exp] = newValue;
            val = newValue;
        });

self.vm[exp] = newValue;这个语句会触发mvvm中SelfValue的setter,以及触发Observer对该对象name属性的监听,即Observer中的Object.defineProperty()中的setter。setter中有通知订阅者的函数dep.notify,Watcher收到通知后就会执行绑定的更新函数。
最后的最后就是效果图啦:

How to understand the principle of two-way binding of Vue data

The above is the detailed content of How to understand the principle of two-way binding of Vue data. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor