Vue2 响应式系统之数组

目录
  • 1、场景
  • 2、场景 2
  • 3、方案
  • 3、收集依赖代码实现
  • 4、通知依赖代码实现
  • 5、测试
  • 6、总结

本文接Vue2响应式系统、Vue2 响应式系统之分支切换 ,响应式系统之嵌套、响应式系统之深度响应还没有看过的小伙伴需要看一下。

1、场景

import { observe } from "./reactive";
import Watcher from "./watcher";
const data = {
    list: ["hello"],
};
observe(data);
const updateComponent = () => {
    for (const item of data.list) {
        console.log(item);
    }
};

new Watcher(updateComponent);
data.list = ["hello", "liang"];

先可以一分钟思考下会输出什么。

虽然 的值是数组,但我们是对 进行整体赋值,所以依旧会触发 的 ,触发 进行重新执行,输出如下:listdata.listdata.listsetWatcher

2、场景 2

import { observe } from "./reactive";
import Watcher from "./watcher";
const data = {
    list: ["hello"],
};
observe(data);
const updateComponent = () => {
    for (const item of data.list) {
        console.log(item);
    }
};
new Watcher(updateComponent);

data.list.push("liang");

先可以一分钟思考下会输出什么。

这次是调用 方法,但我们对 方法什么都没做,因此就不会触发 了。pushpushWatcher

3、方案

为了让 还有数组的其他方法也生效,我们需要去重写它们,通过push代理模式我们可以将数组的原方法先保存起来,然后执行,并且加上自己额外的操作。

/*
 * not type checking this file because flow doesn't play well with
 * dynamically accessing methods on Array prototype
 */

/*
export function def(obj, key, val, enumerable) {
    Object.defineProperty(obj, key, {
        value: val,
        enumerable: !!enumerable,
        writable: true,
        configurable: true,
    });
}
*/
import { def } from "./util";

const arrayProto = Array.prototype;
export const arrayMethods = Object.create(arrayProto);

const methodsToPatch = [
    "push",
    "pop",
    "shift",
    "unshift",
    "splice",
    "sort",
    "reverse",
];

/**
 * Intercept mutating methods and emit events
 */
methodsToPatch.forEach(function (method) {
    // cache original method
    const original = arrayProto[method];
    def(arrayMethods, method, function mutator(...args) {
        const result = original.apply(this, args);
        /*****************这里相当于调用了对象 set 需要通知 watcher ************************/
        // 待补充
        /**************************************************************************** */
        return result;
    });
});

当调用了数组的 或者其他方法,就相当于我们之前重写属性的 ,上边待补充的地方需要做的就是通知 中的 。pushsetdepWatcher

export function defineReactive(obj, key, val, shallow) {
    const property = Object.getOwnPropertyDescriptor(obj, key);
    // 读取用户可能自己定义了的 get、set
    const getter = property && property.get;
    const setter = property && property.set;
    // val 没有传进来话进行手动赋值
    if ((!getter || setter) && arguments.length === 2) {
        val = obj[key];
    }
    const dep = new Dep(); // 持有一个 Dep 对象,用来保存所有依赖于该变量的 Watcher

    let childOb = !shallow && observe(val);
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get: function reactiveGetter() {
            const value = getter ? getter.call(obj) : val;
            if (Dep.target) {
                dep.depend();
            }
            return value;
        },
        set: function reactiveSetter(newVal) {
            const value = getter ? getter.call(obj) : val;

            if (setter) {
                setter.call(obj, newVal);
            } else {
                val = newVal;
            }
            dep.notify();
        },
    });
}

如上边的代码,之前的 是通过闭包,每一个属性都有一个各自的 ,负责收集 和通知 。depdepWatcherWatcher

那么对于数组的话,我们的 放到哪里比较简单呢?dep

回忆一下现在的结构。

const data = {
    list: ["hello"],
};
observe(data);

const updateComponent = () => {
    for (const item of data.list) {
        console.log(item);
    }
};
new Watcher(updateComponent);

上边的代码执行过后会是下图的结构。

list 属性在闭包中拥有了 属性,通过 ,收集到了包含 函数的 。Depnew WatcherupdateCompnentWatcher

同时因为 的 是数组,也就是对象,通过上篇 listvalue["hello"]响应式系统之深度响应(opens new window)我们知道,它也会去调用 函数。Observer

那么,我是不是在 中也加一个 就可以了。ObserverDep

这样当我们调用数组方法去修改 的值的时候,去通知 中的 就可以了。['hello']ObserverDep

3、收集依赖代码实现

按照上边的思路,完善一下 类。Observer

export class Observer {
    constructor(value) {
        /******新增 *************************/
        this.dep = new Dep();
        /************************************/
      	this.walk(value);
    }

    /**
     * 遍历对象所有的属性,调用 defineReactive
     * 拦截对象属性的 get 和 set 方法
     */
    walk(obj) {
        const keys = Object.keys(obj);
        for (let i = 0; i < keys.length; i++) {
            defineReactive(obj, keys[i]);
        }
    }
}

然后在 中,当前 中的 也去收集依赖。getOberverdep

export function defineReactive(obj, key, val, shallow) {
    const property = Object.getOwnPropertyDescriptor(obj, key);
    // 读取用户可能自己定义了的 get、set
    const getter = property && property.get;
    const setter = property && property.set;
    // val 没有传进来话进行手动赋值
    if ((!getter || setter) && arguments.length === 2) {
        val = obj[key];
    }
    const dep = new Dep(); // 持有一个 Dep 对象,用来保存所有依赖于该变量的 Watcher

    let childOb = !shallow && observe(val);
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get: function reactiveGetter() {
            const value = getter ? getter.call(obj) : val;
            if (Dep.target) {
                dep.depend();
                /******新增 *************************/
                if (childOb) {
                    // 当前 value 是数组,去收集依赖
                    if (Array.isArray(value)) {
                        childOb.dep.depend();
                    }
                }
                /************************************/
            }
            return value;
        },
        set: function reactiveSetter(newVal) {
            const value = getter ? getter.call(obj) : val;

            if (setter) {
                setter.call(obj, newVal);
            } else {
                val = newVal;
            }
            dep.notify();
        },
    });
}

4、通知依赖代码实现

我们已经重写了 方法,但直接覆盖全局的 方法肯定是不好的,我们可以在 类中去操作,如果当前 是数组,就去拦截它的 方法。arrayarrrayObservervaluearray

这里就回到 的原型链上了,我们可以通过浏览器自带的 ,将当前对象的原型指向我们重写过的方法即可。js__proto__

考虑兼容性的问题,如果 不存在,我们直接将重写过的方法复制给当前对象即可。__proto__

import { arrayMethods } from './array' // 上边重写的所有数组方法
/* export const hasProto = "__proto__" in {}; */
export class Observer {
    constructor(value) {
        this.dep = new Dep();
      	/******新增 *************************/
        if (Array.isArray(value)) {
            if (hasProto) {
                protoAugment(value, arrayMethods);
            } else {
                copyAugment(value, arrayMethods, arrayKeys);
            }
        /************************************/
        } else {
            this.walk(value);
        }
    }

    /**
     * 遍历对象所有的属性,调用 defineReactive
     * 拦截对象属性的 get 和 set 方法
     */
    walk(obj) {
        const keys = Object.keys(obj);
        for (let i = 0; i < keys.length; i++) {
            defineReactive(obj, keys[i]);
        }
    }
}
/**
 * Augment a target Object or Array by intercepting
 * the prototype chain using __proto__
 */
function protoAugment(target, src) {
    /* eslint-disable no-proto */
    target.__proto__ = src;
    /* eslint-enable no-proto */
}

/**
 * Augment a target Object or Array by defining
 * hidden properties.
 */
/* istanbul ignore next */
function copyAugment(target, src, keys) {
    for (let i = 0, l = keys.length; i < l; i++) {
        const key = keys[i];
        def(target, key, src[key]);
    }
}

还需要考虑一点,数组方法中我们只能拿到 值,那么怎么拿到 对应的 呢。valuevalueObserver

我们只需要在 类中,增加一个属性来指向自身即可。Observe

export class Observer {
    constructor(value) {
        this.dep = new Dep();
        /******新增 *************************/
        def(value, '__ob__', this)
        /************************************/
        if (Array.isArray(value)) {
            if (hasProto) {
                protoAugment(value, arrayMethods);
            } else {
                copyAugment(value, arrayMethods, arrayKeys);
            }
        } else {
            this.walk(value);
        }
    }
  	...
}

回到最开始重写的 方法中,只需要从 中拿到 去通知 即可。array__ob__DepWatcher

/*
 * not type checking this file because flow doesn't play well with
 * dynamically accessing methods on Array prototype
 */

import { def } from "./util";

const arrayProto = Array.prototype;
export const arrayMethods = Object.create(arrayProto);

const methodsToPatch = [
    "push",
    "pop",
    "shift",
    "unshift",
    "splice",
    "sort",
    "reverse",
];

/**
 * Intercept mutating methods and emit events
 */
methodsToPatch.forEach(function (method) {
    // cache original method
    const original = arrayProto[method];
    def(arrayMethods, method, function mutator(...args) {
        const result = original.apply(this, args);
        /*****************这里相当于调用了对象 set 需要通知 watcher ************************/
        const ob = this.__ob__;
        // notify change
        ob.dep.notify();
        /**************************************************************************** */
        return result;
    });
});

5、测试

import { observe } from "./reactive";
import Watcher from "./watcher";
const data = {
    list: ["hello"],
};
observe(data);
const updateComponent = () => {
    for (const item of data.list) {
        console.log(item);
    }
};

new Watcher(updateComponent);
data.list.push("liang");

这样当调用 方法的时候,就会触发相应的 来执行 函数了。pushWatcherupdateComponent

当前的依赖就变成了下边的样子:

6、总结

对于数组的响应式我们解决了三个问题,依赖放在哪里、收集依赖和通知依赖。

我们来和普通对象属性进行一下对比。

到此这篇关于Vue2 响应式系统之数组的文章就介绍到这了,更多相关Vue2 数组内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Vue2 响应式系统之异步队列

    目录 场景 解决方案 代码实现 执行结果 总结 试想一下如果这里的 console.log 是渲染页面,那改变一次值就刷新一下页面,会造成严重的性能问题,页面也会不停的改变. 场景 import { observe } from "./reactive"; import Watcher from "./watcher"; const data = { a: 1, b: 2, c: 3, }; observe(data); const updateComponent

  • Vue2 响应式系统之分支切换

    目录 场景 observer(data) new Watcher(updateComponent) data.ok = false data.text = "hello, liang" 问题 去重 重置 测试 总结 场景 我们考虑一下下边的代码会输出什么. import { observe } from "./reactive"; import Watcher from "./watcher"; const data = { text: &quo

  • Vue2响应式系统之嵌套

    目录 1.场景 2.执行过程 3.修复 4.测试 5.总结 1.场景 在 开发中肯定存在组件嵌套组件的情况,类似于下边的样子.Vue <!-- parent-component --> <div> <my-component :text="inner"></my-component> {{ text }} <div> <!-- my-component--> <div>{{ text }}</di

  • Vue2中无法检测到数组变动的原因及解决

    目录 解决方法 由于JavaScript 的限制,Vue 不能检测以下数组的变动: 当利用索引直接设置一个数组项时,例如:vm.items[indexOfItem] = newValue 当修改数组的长度时,例如:vm.items.length = newLength var vm = new Vue({ data: { items: ['a', 'b', 'c'] } }) vm.items[1] = 'x' // 不是响应性的 vm.items.length = 2 // 不是响应性的 解决

  • Vue2响应式系统介绍

    目录 一.响应式系统要干什么 二.响应式数据 三.保存当前正在执行的函数 四.响应式数据 五.Observer 对象 六.测试 七.总结 前言: 目前工作中大概有 的需求是在用 的技术栈,所谓知其然更要知其所以然,为了更好的使用 .更快的排查问题,最近学习了源码相关的一些知识,虽然网上总结 的很多很多了,不少自己一个,但也不多自己一个,欢迎一起讨论学习,发现问题欢迎指出.40%Vue2VueVue 一.响应式系统要干什么 回到最简单的代码: data = { text: 'hello, worl

  • vue2.x数组劫持原理的实现

    接上篇Vue2.x 对象劫持,继续来写数组劫持 实现原理: 1 重新定义原生数组方法push unshift shift pop splice sort reverse 因为这些方法可以修改原数组. 2 拿到原生数组方法 Object.create(Array.prototype) 3 AOP拦截,再执行重写数组方法前,先执行原生数组方法 核心监听Observer代码 // 把data中的数据 都使用Object.defineProperty重新定义 es5 // Object.definePr

  • Vue2 响应式系统之深度响应

    目录 1.场景 2.方案 3.场景2 4.总结 1.场景 import { observe } from "./reactive"; import Watcher from "./watcher"; const data = { text: { innerText: { childText: "hello", }, }, }; observe(data); const updateComponent = () => { console.lo

  • Vue2 响应式系统之数组

    目录 1.场景 2.场景 2 3.方案 3.收集依赖代码实现 4.通知依赖代码实现 5.测试 6.总结 本文接Vue2响应式系统.Vue2 响应式系统之分支切换 ,响应式系统之嵌套.响应式系统之深度响应还没有看过的小伙伴需要看一下. 1.场景 import { observe } from "./reactive"; import Watcher from "./watcher"; const data = { list: ["hello"],

  • Vue2响应式系统之set和delete

    目录 1.数组集 2.数组 del 3.对象 set 4.对象 del 5.总结 1.数组集 import { observe } from "./reactive"; import Watcher from "./watcher"; const data = { list: [1, 2], }; observe(data); const updateComponent = () => { console.log(data.list); }; new Watc

  • 这应该是最详细的响应式系统讲解了

    前言 本文从一个简单的双向绑定开始,逐步升级到由defineProperty和Proxy分别实现的响应式系统,注重入手思路,抓住关键细节,希望能对你有所帮助. 一.极简双向绑定 首先从最简单的双向绑定入手: // html <input type="text" id="input"> <span id="span"></span> // js let input = document.getElementByI

  • Vue响应式系统的原理详解

    目录 vue响应式系统的基本原理 1.回顾一下Object.defineProperty的用法 2.实战1:使用 Object.defineProperty 对 person的age属性 进行监听 3.数据代理 4.vue中实现响应式思路 总结 1.Vue中的数据代理: 2.Vue中数据代理的好处: 3.基本原理: 4.vue中实现响应式思路 vue响应式系统的基本原理 我们使用vue时,对数据进行操作,就能影响对应的视图.那么这种机制是怎么实现的呢? 思考一下,是不是就好像我们对数据的操作 被

  • 手写 Vue3 响应式系统(核心就一个数据结构)

    目录 前言 响应式 总结 前言 响应式是 Vue 的特色,如果你简历里写了 Vue 项目,那基本都会问响应式实现原理.而且不只是 Vue,状态管理库 Mobx 也是基于响应式实现的.那响应式是具体怎么实现的呢?与其空谈原理,不如让我们来手写一个简易版吧. 响应式 首先,什么是响应式呢? 响应式就是被观察的数据变化的时候做一系列联动处理.就像一个社会热点事件,当它有消息更新的时候,各方媒体都会跟进做相关报道.这里社会热点事件就是被观察的目标.那在前端框架里,这个被观察的目标是什么呢?很明显,是状态

随机推荐