search
HomeWeb Front-endJS TutorialAnalysis of Vue data responsiveness principle
Analysis of Vue data responsiveness principleMay 12, 2018 am 11:23 AM
analyzeprincipleresponse

This time I will bring you an analysis of the principles of Vue data responsiveness. What are the precautions of Vue data responsiveness? The following is a practical case, let’s take a look.

Preface

Vue’s data response mainly relies on Object.defineProperty(), so what is the whole process like? Taking the path of Vue with our own ideas actually means taking the principles of Vue as the end point. Let's reverse the implementation process.

The code in this article is a low-configuration version, and many places are not rigorous. For example, if(typeof obj === 'object') is to determine whether obj is an object, although obj may also be Array and other types of data, but for the sake of simplicity, this article will write it directly to represent the judgment object. For arrays, use Array.isArray().

Transform data

Let’s first try to write a function for transforming objects:

Why should we write this first? What about functions? Because transforming data is the most basic and important step, all subsequent steps will depend on this step.

// 代码 1.1
function defineReactive (obj,key,val) {
 Object.defineProperty(obj,key,{
  enumerable: true,
  configurable: true,
  get: function () {
   return val;
  },
  set: function (newVal) {
   //判断新值与旧值是否相等
   //判断的后半段是为了验证新值与旧值都为NaN的情况 NaN不等于自身
   if(newVal === val || (newVal !== newVal && value !== value)){
    return ;
   }
   val = newVal;
  }
 });
}

For example, const obj = {}, and then call the defineReactive(obj,'a',2) method. At this time, within the function, val=2, and then every time the value of obj.a is obtained They all get the value of val. When setting obj.a, they also set the value of val. (Every time defineReactive is called, a closure will be generated to save the value of val);

Process Discussion

After verification, this function was found It can indeed be used. Then let’s discuss the response process:

  1. Input data

  2. Transform data (defineReactive() )

  3. If the data changes=> trigger event

Let’s look at the third step. How does the data change trigger subsequent events? Think about it carefully, if you want to change the data, you must set the data first, then we can just add the method to set() and it will be ok.

Then there is another important question:

Dependency collection

How do we Do you know what event will be triggered after the data changes? In Vue:

Use data => View; Data is used to render the view, so it is the best time to collect dependencies when obtaining data. Vue generates a Dep instance when transforming the data attributes. Used to collect dependencies.

// 代码 1.2
class Dep {
 constructor(){
  //订阅的信息
  this.subs = [];
 }
 addSub(sub){
  this.subs.push(sub);
 }
 removeSub (sub) {
  remove(this.subs, sub);
 }
 //此方法的作用等同于 this.subs.push(Watcher);
 depend(){
  if (Dep.target) {
   Dep.target.addDep(this);
  }
 }
 //这个方法就是发布通知了 告诉你 有改变啦
 notify(){
  const subs = this.subs.slice()
  for (let i = 0, l = subs.length; i <p style="text-align: left;">Code 1.2 is part of the code of Dep. For the time being, you only need to know the functions of the two methods</p><ol class=" list-paddingleft-2">
<li><p style="text-align: left;">depend() --- can be understood as collecting dependencies event, without considering other aspects, the function is equivalent to addSub()</p></li>
<li><p style="text-align: left;">notify() --- This method is more intuitive and executes all dependent update() methods. Just change the view later and so on. </p></li>
</ol><p style="text-align: left;">This article mainly discusses the process of data response and does not discuss the Watcher class in depth, so you only need to know the functions of the methods in Dep. </p><p style="text-align: left;">Then the code is changed to 1.1</p><pre class="brush:php;toolbar:false">//代码 1.3
function defineReactive (obj,key,val) {
 const dep = new Dep();
 Object.defineProperty(obj,key,{
  enumerable: true,
  configurable: true,
  get: function () {
   if(Dep.target){
    //收集依赖 等同于 dep.addSub(Dep.target)
    dep.depend()
   }
   return val;
  },
  set: function (newVal) {
   if(newVal === val || (newVal !== newVal && val !== val)){
    return ;
   }
   val = newVal;
   //发布改变
   dep.notify();
  }
 });
}

There is a doubt in this code, what is Dep.target? Why do we need Dep.target to collect dependencies?

  1. Dep is a class, and Dep.target is an attribute of the class, not an attribute of the dep instance.

  2. The Dep class is available globally, so Dep.target can be accessed globally and its value can be changed arbitrarily.

  3. get This method is very common to use, and it is impossible to call dep.depend() every time you use it to obtain data values.

  4. dep.depend() is actually dep.addSub(Dep.target).

  5. The best way is to set Dep.target to an object before use, and set Dep.target = null after the subscription is completed.

Verification

It’s time to verify the availability of a wave of codes

//代码 1.4
const obj = {};//这一句是不是感觉很熟悉 就相当于初始化vue的data ---- data:{obj:{}};
//低配的不能再低配的watcher对象(源码中是一个类,我这用一个对象代替了)
const watcher = {
 addDep:function (dep) {
  dep.addSub(this);
 },
 update:function(){
  html();
 }
}
//假装这个是渲染页面的
function html () {
 document.querySelector('body').innerHTML = obj.html;
}
defineReactive(obj,'html','how are you');//定义响应式的数据
Dep.target = watcher;
html();//第一次渲染界面
Dep.target = null;

此时浏览器上的界面是这样的

然后在下打开了控制台开始调试,输入:

obj.html = 'I am fine thank you'

然后就发现,按下回车的那一瞬间,奇迹发生了,页面变成了

结尾

Vue数据响应的设计模式和订阅发布模式有一点像,但是不同,每一个dep实例就是一个订阅中心,每一次发布都会把所有的订阅全部发布出去。

Vue的响应式原理其实还有很大一部分,本文主要讨论了Vue是如何让数据进行响应,但是实际上,一般的数据都是很多的,一个数据被多处使用,改变数据之后观察新值,如何观察、如何订阅、如何调度,都还有很大一部分没有讨论。主要的三个类Dep(收集依赖)、Observer(观察数据)、Watcher(订阅者,若数据有变化通知订阅者),都只提了一点点。

之前写有一篇Vue响应式----数组变异方法,针对Vue中对数组的改造进行讨论。当然之后有更多其他的文章,整个数据响应流程还有很多内容,三个主要的类都还没有讨论完。

其实阅读源码不仅仅是为了知道源码是如何工作的,更重要的是学习作者的思路与方法,我写的文章都不长,希望自己能够每次专注一个点,能够真真实实领悟到这一个点的原理。当然也想控制阅读时间,免得大家看到一半就关闭了。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

React Form组件封装步骤详解

JS跨域POST实现步骤详解

The above is the detailed content of Analysis of Vue data responsiveness principle. 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
如何使用MySQL数据库进行预测和预测分析?如何使用MySQL数据库进行预测和预测分析?Jul 12, 2023 pm 08:43 PM

如何使用MySQL数据库进行预测和预测分析?概述:预测和预测分析在数据分析中扮演着重要角色。MySQL作为一种广泛使用的关系型数据库管理系统,也可以用于预测和预测分析任务。本文将介绍如何使用MySQL进行预测和预测分析,并提供相关的代码示例。数据准备:首先,我们需要准备相关的数据。假设我们要进行销售预测,我们需要具有销售数据的表。在MySQL中,我们可以使用

如何使用 Go 语言进行数据可视化分析?如何使用 Go 语言进行数据可视化分析?Jun 10, 2023 am 10:46 AM

随着大数据时代的到来,数据可视化分析在各行各业中扮演着至关重要的角色。而Go语言作为一种快速、高效、安全的编程语言,也逐渐在数据可视化分析领域占据一席之地。本文将探讨如何使用Go语言进行数据可视化分析。一、Go语言常用的数据可视化库Plotly:可用于在浏览器中创建交互式的图形,支持多种图形类型,如线图、条形图、散点图、热力图等。Gonum/plo

Linux下的实时日志监控与分析Linux下的实时日志监控与分析Jul 29, 2023 am 08:06 AM

Linux下的实时日志监控与分析在日常的系统管理和故障排查中,日志是一个非常重要的数据来源。通过对系统日志的实时监控和分析,我们可以及时发现异常情况并进行相应的处理。本文将介绍Linux下如何进行实时日志监控和分析,并提供相应的代码示例。一、实时日志监控在Linux下,最常用的日志系统是rsyslog。通过配置rsyslog,我们可以实现将不同应用程序的日志

统计分析法的步骤统计分析法的步骤Jun 28, 2023 pm 03:27 PM

统计分析,常指对收集到的有关数据资料进行整理归类并进行解释的过程。统计分析的基本步骤包括:1、收集数据;2、整理数据;3、分析数据。

如何使用PHP进行性能分析和调优如何使用PHP进行性能分析和调优Jun 06, 2023 pm 01:21 PM

作为一种流行的服务端语言,PHP在网站开发和运行中扮演着重要的角色。然而,随着PHP代码量的不断增加和应用程序的复杂性提高,性能瓶颈也越来越容易出现。为了避免这种问题,我们需要进行性能分析和调优。本文将简单介绍如何使用PHP进行性能分析和调优,为您的应用程序提供更高效的运行环境。一、PHP性能分析工具1.XdebugXdebug是一款广泛使用的代码分析工具,

最近大火的Diffusion Model,首篇扩散生成模型综述!最近大火的Diffusion Model,首篇扩散生成模型综述!Apr 09, 2023 pm 08:31 PM

本综述(Diffusion Models: A Comprehensive Survey of Methods and Applications)来自加州大学&amp;Google Research的Ming-Hsuan Yang、北京大学崔斌实验室以及CMU、UCLA、蒙特利尔Mila研究院等众研究团队,首次对现有的扩散生成模型(diffusion model)进行了全面的总结分析,从diffusion model算法细化分类、和其他五大生成模型的关联以及在七大领域中的应用等方面展开,

如何利用PHP和Elasticsearch实现结果聚合和分析如何利用PHP和Elasticsearch实现结果聚合和分析Jul 17, 2023 pm 01:05 PM

如何利用PHP和Elasticsearch实现结果聚合和分析引言:随着互联网和信息技术的迅猛发展,数据量的爆炸式增长使得数据的存储、处理、分析变得越来越重要。而Elasticsearch作为一个开源的分布式搜索和分析引擎,具有强大的全文检索、实时分析和数据聚合能力,已经被广泛应用于各大行业中。在本文中,我们将介绍如何利用PHP和Elasticsearch结合

如何使用 Go 语言进行大数据分析?如何使用 Go 语言进行大数据分析?Jun 11, 2023 am 11:11 AM

随着数据规模逐渐增大,大数据分析变得越来越重要。而Go语言作为一门快速、轻量级的编程语言,也成为了越来越多数据科学家和工程师的选择。本文将介绍如何使用Go语言进行大数据分析。数据采集在开始大数据分析之前,我们需要先采集数据。Go语言有很多包可以用于数据采集,例如“net/http”、“io/ioutil”等。通过这些包,我们可以从网站、API、日志

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft