search
HomeWeb Front-endVue.jsAnalyze 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.

Analyze the two-way binding principle of observer data in Vue (code sharing)

vueData two-way binding principle and simple implementation

Analyze the two-way binding principle of observer data in Vue (code sharing)

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 operated

  • propThe 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 the configurable of this property is true, this property description The character can be changed and the attribute can be deleted from the corresponding object. Default is false.

  • enumerable This attribute can appear in the object only if the enumerable of the attribute is true in the enumeration properties. Default is false. The data descriptor also has the following optional key values:

  • valueThe value corresponding to this attribute. Can be any valid JavaScript value (numeric value, object, function, etc.). Default is undefined.

  • writableIf and only if the writable of the property is true, the property can be assigned the operator Change. Default is false. The access descriptor also has the following optional key values:

  • getA method that provides a getter for the property, if there is no getter is undefined. The return value of this method is used as the attribute value. Default is undefined.

  • set is a method that provides setter to the property. If there is no setter, it will be undefined. This method will accept a unique parameter and assign the parameter's new value to the property. Default is undefined.

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 chuchur

It’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,作为连接ObserverCompile的桥梁,能够订阅并收到每个属性变动的通知,执行指令绑定的相应回调函数,从而更新视图

大概的流程图如下: 

Analyze the two-way binding principle of observer data in Vue (code sharing)

实现Observer

将需要observe的数据对象进行递归遍历,包括子属性对象的属性,都加上settergetter这样的话,给这个对象的某个值赋值,就会触发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!

Statement
This article is reproduced at:禅境花园. If there is any infringement, please contact admin@php.cn delete
What Happens When the Vue.js Virtual DOM Detects a Change?What Happens When the Vue.js Virtual DOM Detects a Change?May 14, 2025 am 12:12 AM

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?May 13, 2025 pm 04:05 PM

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool