Vue2剥丝抽茧-响应式系统之数组

人工智能2025-11-05 09:39:1064

场景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"];

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

... ...

虽然 list 的茧响值是数组,但我们是应式对 data.list 进行整体赋值,所以依旧会触发 data.list 的系统 set ,触发 Watcher 进行重新执行,免费信息发布网数组输出如下:

场景 2import { 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");

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

... ...

这次是茧响调用 push 方法,但我们对 push 方法什么都没做,应式因此就不会触发 Watcher 了。系统

方案

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

/

*

* not type checking this file because flow doesnt 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);

/

本文地址:http://www.bzve.cn/html/987a62398389.html
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

全站热门

Ryzen5(探索Ryzen5的高性能特点及其在市场上的竞争力)

阿里巴巴如何管理代码分支?

16岁的我是如何成为全栈开发人员的?

AngularJS的七种常见优秀实践

一.修改/etc/network/interfaces,注释自动获取IP,并添加自动从网卡获取地址。   #auto lo   #iface lo inet lockloop   auto eth0   二. 修改/etc/network/interfaces,添加静态IP信息   iface eth0 inet static   address ***.***.***.***   netmask 255.255.255.0   gateway ***.***.***.254   三.修改/etc/resolv.conf,设置DNS   namaserver ***.***.***.***   nameserver ***.***.***.***   四.重启网络   管理员身份执行 /etc/init.d/networking restart   五.重新启动网络,enjoy Ubuntu

如何在OpenStack中从命令行创建可用区?

如何提升Kubernetes生产力?我有5个实用技巧分享给你

为何我建议1-3年的Java程序员仔细看看这篇文章

热门文章

友情链接

滇ICP备2023006006号-39