Home Web Front-end JS Tutorial Detailed explanation of steps to use Vue data response

Detailed explanation of steps to use Vue data response

May 31, 2018 am 10:30 AM
use step Detailed explanation

This time I will bring you a detailed explanation of the steps for using Vue data response. What are the precautions when using Vue data response? Here are practical cases, 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

// 代码 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;

  }

 });

}

Copy after login

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

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

// 代码 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 < l; i++) {

   subs[i].update();

  }

 }

}

Dep.target = null;

Copy after login

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

  1. depend() --- can be understood as collecting dependencies event, without considering other aspects, the function is equivalent to addSub()

  2. notify() --- This method is more intuitive and executes all dependent update() methods. Just change the view later and so on.

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.

Then the code is changed to 1.1

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

//代码 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();

  }

 });

}

Copy after login

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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

//代码 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;

Copy after login

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

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

1

obj.html = 'I am fine thank you'

Copy after login

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

结尾

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

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

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

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

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

推荐阅读:

怎样使用Vue实现树形视图数据

JS对DOM树实现遍历有哪些方法

The above is the detailed content of Detailed explanation of steps to use Vue data response. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to make Google Maps the default map in iPhone How to make Google Maps the default map in iPhone Apr 17, 2024 pm 07:34 PM

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

Steps to upgrade to the latest version of WeChat (Easily master the upgrade method to the latest version of WeChat) Steps to upgrade to the latest version of WeChat (Easily master the upgrade method to the latest version of WeChat) Jun 01, 2024 pm 10:24 PM

WeChat is one of the social media platforms in China that continuously launches new versions to provide a better user experience. Upgrading WeChat to the latest version is very important to keep in touch with family and colleagues, to stay in touch with friends, and to keep abreast of the latest developments. 1. Understand the features and improvements of the latest version. It is very important to understand the features and improvements of the latest version before upgrading WeChat. For performance improvements and bug fixes, you can learn about the various new features brought by the new version by checking the update notes on the WeChat official website or app store. 2. Check the current WeChat version We need to check the WeChat version currently installed on the mobile phone before upgrading WeChat. Click to open the WeChat application "Me" and then select the menu "About" where you can see the current WeChat version number. 3. Open the app

This Apple ID is not yet in use in the iTunes Store: Fix This Apple ID is not yet in use in the iTunes Store: Fix Jun 10, 2024 pm 05:42 PM

When logging into iTunesStore using AppleID, this error saying "This AppleID has not been used in iTunesStore" may be thrown on the screen. There are no error messages to worry about, you can fix them by following these solution sets. Fix 1 – Change Shipping Address The main reason why this prompt appears in iTunes Store is that you don’t have the correct address in your AppleID profile. Step 1 – First, open iPhone Settings on your iPhone. Step 2 – AppleID should be on top of all other settings. So, open it. Step 3 – Once there, open the “Payment & Shipping” option. Step 4 – Verify your access using Face ID. step

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

Shazam app not working in iPhone: Fix Shazam app not working in iPhone: Fix Jun 08, 2024 pm 12:36 PM

Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

iPhone screenshots not working: How to fix it iPhone screenshots not working: How to fix it May 03, 2024 pm 09:16 PM

Screenshot feature not working on your iPhone? Taking a screenshot is very easy as you just need to hold down the Volume Up button and the Power button at the same time to grab your phone screen. However, there are other ways to capture frames on the device. Fix 1 – Using Assistive Touch Take a screenshot using the Assistive Touch feature. Step 1 – Go to your phone settings. Step 2 – Next, tap to open Accessibility settings. Step 3 – Open Touch settings. Step 4 – Next, open the Assistive Touch settings. Step 5 – Turn on Assistive Touch on your phone. Step 6 – Open “Customize Top Menu” to access it. Step 7 – Now you just need to link any of these functions to your screen capture. So click on the first

Clock app missing in iPhone: How to fix it Clock app missing in iPhone: How to fix it May 03, 2024 pm 09:19 PM

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

See all articles