vue2如何重写数组

Vue中使用Object.defineProperty重新将对象中的属性定义,如果是数组的话需要重写数组原型上的方法。

代码如下:

 1 function notify() {
 2     console.log('视图更新')
 3 }
 4 let data = {
 5     name: 'jw',
 6     age: 18,
 7     arr: [1,2,3]
 8 }
 9 // 重写数组的方法
10 let oldProtoMehtods = Array.prototype;
11 let proto = Object.create(oldProtoMehtods);
12 ['push', 'pop', 'shift', 'unshift'].forEach(method => {
13     proto[method] = function (...args) {
14         let inserted;
15         switch (method) {
16             case 'push':
17             case 'unshift':
18                 inserted = args;
19                 break;
20         }
21         observerArray(inserted)
22         notify();
23         oldProtoMehtods[method].call(this, ...args)
24     }
25 })
26 function observerArray(obj) { // 观察数组中的每一项
27     for (let i = 0; i < obj.length; i++) {
28         observer(obj[i]);
29     }
30 }
31 function observer(obj) {
32     if(typeof obj !== 'object'){
33         return obj
34     }
35     if (Array.isArray(obj)) {
36         obj.__proto__ = proto
37         observerArray(obj);
38     }else{
39         for (let key in obj) {
40             defineReactive(obj, key, obj[key]);
41         }
42     }
43 }
44 function defineReactive(obj, key, value) {
45     observer(value); // 再一次循环value
46     Object.defineProperty(obj, key, { // 不支持数组
47         get() {
48             return value;
49         },
50         set(val) {
51             notify();
52             observer(val);
53             value = val;
54         }
55     });
56 }
57 observer(data);
58 data.arr.push({name:'jw'})
59 console.log(data.arr);

 

posted @ 2023-06-13 09:37  飞翔的蜗牛~  阅读(354)  评论(0编辑  收藏  举报
Live2D