This is the 25th day of my participation in Gwen Challenge

One, foreword

The previous chapter mainly introduced the asynchronous update process of Vue, mainly involving the following points:

  • Why do asynchronous updates
  • The realization idea of asynchronous update
  • The location of the data change cache
  • Cache watcher update logic
  • Vm. $nextTick gets the updated DOM
  • Testing asynchronous updates

This article, the dependency collection of arrays


Second, the dependency collection of arrays

Previously on 1

In the previous article, we addressed the dependency collection of objects,

  • The value goes through the getter for dependency collection.
  • Setters, update the view;
However, array types do not go object.defineProperty so how do arrays do dependency collection? How do I update views when data changes?Copy the code

In this article, we will continue to improve the dependency collection of arrays.

2. Reactive implementation of arrays

In a reactive implementation, the array data type is the render Watcher on which the collection array depends by overriding seven methods that can change the original array and trigger the corresponding Watcher update when the array is updatedCopy the code

3. Dependency collection schemes for arrays

Object dependency collection scheme: Add a DEP property to each property of an object for dependency collection. Similarly, add a DEP property to an array for dependency collection. When an array is updated, notify the array dependency to update the viewCopy the code

4. Arrays depend on collection entries

class Observer {
  constructor(value) {
    Object.defineProperty(value, '__ob__', {
      value:this.enumerable:false
    });
    if (isArray(value)) {
      value.__proto__ = arrayMethods;
      this.observeArray(value);
    } else {
      this.walk(value); }}Copy the code
Data of an object or array type creates an Observer instance from a New Observer, so a value in an Observer can be an array or an object. In an Observer class, value (this) refers to an Observer instance and adds an '__ob__' attribute to it. Thus, each object or array has an __ob__ attribute, so, You can add a DEP attribute to an observer instance here. This is equivalent to adding a DEP attribute to either the array or the object itself. This allows you to fetch the DEP on an object or an array via 'value.__ob__. The view update operation is triggered through the watcher collected in the DEPCopy the code

Three, the end

This article mainly introduces the principle of array dependent collection

  • Reactive implementation of arrays
  • Array dependency collection scheme introduction

Next, the implementation of array dependent collection