1. We rewrite a file
Creating array.js
2. get an array of all methods
let oldArrayProtoMethods = Array.prototype;
3. Create a new method Object.create ()
export let arrayMethod = Object.create(oldArrayProtoMethods);
4. The method of Statement 7
let methods = [ 'push', 'pop', 'unshift', 'shift', 'sort', 'splice', 'reverse' ]
6. The method of adding their array rewrite operation
methods.forEach (Method => { the console.log (Method) arrayMethod [Method] = function (... args) { the let R & lt = oldArrayProtoMethods [Method] .apply ( the this , args) the console.log ( ' call data updated method ' ) } })
Iterate method to get the original array of ways to change this point to point to arrayMethod
7. These methods prototype array mount
IF (Array.isArray (Data)) { // Only one item of each array also need to intercept the array method of observing the console.log ( ' monitor array ' ) data._proto = arrayMethod }
8. Test
index.js
import Vue from '../source/src/index'; let vm = new Vue({ el: '#app', data() { return { msg: 'hello', school: { name: 'zf', age: 10 }, arr: [1, 2, 3] } }, computed: { }, watch: { } }) vm.arr.push(1111) console.log(vm.arr) // hello
9. Test Results
10.push into the array could be a target we should object inside the array of items that listens
First clear only push unshift slice has an array of new features so we have to listen in these methods
let inserted; switch (key) { case 'push': case 'unshift': inserted = args break;
// 获取新增的 inserted = args.slice(2) break; default: break; } if (inserted) observerArray(inserted)
11. traversal monitor loop through the array in order to add items to the new array each observation
export function observerArray(inserted) { for (let i = 0; i < inserted.length; i++) { observe(inserted[i]) } }
12. Each entry in the array observation observer.js
// Each array entry observation observerArray (data)
13. Test
index.js
import Vue from '../source/src/index'; let vm = new Vue({ el: '#app', data() { return { msg: 'hello', school: { name: 'zf', age: 10 }, arr: [1, 2, 3] } }, computed: { }, watch: { } }) vm.arr.push({ a: 1 }) console.log(vm.arr[3].a) // hello
14. Test results
Cloud code: https://gitee.com/guangzhou110/handwritten_vue/tree/master/vue%20%E6%95%B0%E7%BB%84%E5%8A%AB%E6%8C%81