Vue2剥丝抽茧-响应式系统之数组
场景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
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。