Analyze the two-way binding principle of observer data in Vue (code sharing)
In the previous article "A brief analysis of some operating methods of Array objects in JS (with code)", we learned about some operating methods of Array objects in JS. The following article will give you an understanding of the two-way binding principle of observer data in Vue. Let's take a look.

vueData two-way binding principle and simple implementation

1 )vue data two-way binding principle-observer
2)vue data two-way binding principle-wather
3)vue data Two-way binding principle - parser Complie
vueData two-way binding principle, and simple implementation
Fuck meow's underlying principle, framework core, I only use Jquery when writing code.
Personally, I feel that no matter whether we have been interacting with it for a long time, we should still look at the core things. Learn more about how experts achieve it, so that you can learn more knowledge and grow and progress. If someone asked one day about the implementation principle of a certain kind of frame underwear, they would just be confused.
The ways to implement data binding are roughly as follows:
-
Publisher-Subscriber Pattern (
backbone.js) Dirty value checking (
angular.js)Data hijacking (
vue.js)
vue.js uses data hijacking combined with the publisher-subscriber model to hijack each property through Object.defineProperty() The setter and getter publish messages to subscribers when data changes, triggering corresponding listening callbacks.
If you have written C#winform custom controls, I want to better understand the subsequent logic and implementation principles
When in C# If a property of the control changes, refresh the view
priveate int a ;
public int A
{
get { return a; }
set { if(a!=value){a = value; Invalidate(); } }
}
# 当a的值发生变化, 就重绘视图Let’s take a look at the Object.defineProperty(obj, prop, descriptor) method
Address: https://developer. mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
Object.defineProperty()The method will define an object directly New properties, or modify existing properties of an object, and returns the object.
objThe target object that needs to be operatedpropThe target object needs to be defined or modified The name of the attribute.descriptorDescriptor of the attribute to be defined or modified
<strong>descriptor</strong>
configurableIf and only if theconfigurableof this property istrue, this property description The character can be changed and the attribute can be deleted from the corresponding object. Default isfalse.enumerableThis attribute can appear in the object only if theenumerableof the attribute istruein the enumeration properties. Default isfalse. The data descriptor also has the following optional key values:valueThe value corresponding to this attribute. Can be any validJavaScriptvalue (numeric value, object, function, etc.). Default isundefined.writableIf and only if thewritableof the property istrue, the property can be assigned the operator Change. Default isfalse. The access descriptor also has the following optional key values:getA method that provides agetterfor the property, if there is nogetterisundefined. The return value of this method is used as the attribute value. Default isundefined.set is a method that provides
setterto the property. If there is nosetter, it will beundefined. This method will accept a unique parameter and assign the parameter's new value to the property. Default isundefined.
Let’s first implement a simple data hijacking
var A = {};
var a = "";
Object.defineProperty(A, "a", {
set: function (value) {
a = value;
},
get: function () {
return "My name is " + a;
},
});
A.a = "chuchur";
console.log(A.a); // My name is chuchurIt’s not just that simple, let’s take a look at the code of vue
<div id="app">
<input type="text" v-model="word" />
<p>{{word}}</p>
<button v-on:click="sayHi">change model</button>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
word: "Hello World!",
},
methods: {
sayHi: function () {
this.word = "Hi, everybody!";
},
},
});
</script> For the simple data hijacking that has been implemented, if there are multiple attributes, it is necessary to implement a data listener Observer, which can monitor all attributes of the data object, and a subscriber DepTo collect changes in these attributes to notify subscribers of the
element node’s v-model, v-on:click, you need to implement a command parser Compile , scan and parse the instructions of each element node, replace the data according to the instruction template, and bind the corresponding update function
最后实现一个订阅者Watcher,作为连接Observer和Compile的桥梁,能够订阅并收到每个属性变动的通知,执行指令绑定的相应回调函数,从而更新视图
大概的流程图如下:

实现Observer
将需要observe的数据对象进行递归遍历,包括子属性对象的属性,都加上setter和getter这样的话,给这个对象的某个值赋值,就会触发setter,那么就能监听到了数据变化
// observe
function observe(data) {
if (data && typeof data === "object") {
// 取出所有属性遍历
Object.keys(data).forEach(function (key) {
defineReactive(data, key, data[key]);
});
}
return;
}
function defineReactive(data, key, val) {
observe(val); // 监听子属性
Object.defineProperty(data, key, {
enumerable: true, // 可枚举
configurable: false, // 不能再define
get: function () {
return val;
},
set: function (value) {
console.log("监听到值变化了: ", val, "==>", value);
val = value;
},
});
}
var A = {
fristName: "chuchur",
age: 29,
};
observe(A);
A.fristName = "nana"; //监听到值变化了: chuchur ==> nana
A.age = 30; //监听到值变化了: 29 ==> 30这样就实现了多个属性的监听,接下来就是实现订阅器Dep,当这些属性变化的时候,触发通知notify,告诉执行订阅者执行更新函数
//Dep
function Dep() {
this.subs = [];
}
Dep.prototype = {
addSub: function (sub) {
this.subs.push(sub);
},
notify: function () {
this.subs.forEach(function (sub) {
sub.update();
});
},
};把订阅器植入到监听器里
function defineReactive(data, key, val) {
var dep = new Dep()
observe(val); //监听子属性
Object.defineProperty(data, key, {
set: function(value) {
dep.notify() //发出通知, 我被改变了
}
});
}至此,简陋的监听器就实现完成了,接下来继续完成Watcher。
推荐学习:vue.js教程
The above is the detailed content of Analyze the two-way binding principle of observer data in Vue (code sharing). For more information, please follow other related articles on the PHP Chinese website!
Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AMNetflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.
The Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AMNetflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.
React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AMNetflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema
The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AMNetflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.
React, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AMNetflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.
Vue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AMVue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.
Vue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AMVue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.
Vue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AMVue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment







