vue數據響應式原理 - 數組的響應式


vue 改寫了數組的七個方法:push、pop、shift、unshift、splice、sort、reverse。使數組改變的時候能夠觸發響應式,先把原來的 Array.prototype 的方法備份一份,再進行重寫。

vue 的數組響應式是如何實現的?

     以 Array.prototype 為原型,創建了一個 arrayMethods 的對象( Object.create(Array.prototype)),然后使用了一個強硬的手段,es6的語法,Object.setPrototypeOf(obj, arrayMethods),強制的讓  數組 的原型 __proto__指向了 arrayMethods,這樣就會觸發重寫的數組方法。

 文件目錄:

 

 index.js

import observe from './observe'; let obj = { a: { m: { n: { e: { f: 5 } } } }, b: 3, g: [1,2,3] }; observe(obj); obj.g.splice(2,1,88); console.log(obj.g);

observe.js

import Observer from './Observer.js'; // 創建 observe 函數,注意函數的名字沒有r
export default function observe (value) { // 函數只為對象服務
    if (typeof value !== 'object') return; // 定義 ob
 let ob; if (typeof value.__ob__ !== 'undefined') { ob = value.__ob__; } else { ob = new Observer(value); } return ob; }

Observer.js

import { def } from './utils.js'; import defineReactive from './defineReactive.js'; import { arrayMethods } from './array.js'; import observe from './observe.js'; export default class Observer { constructor(value) { // 給實例(構造函數中的this表示實例)添加了__ob__屬性
        def(value, '__ob__', this, false); // Observer類的目的是:將一個正常的 object 轉換為每個層級的屬性都是響應式(可以被偵測的)的 object
        // 檢查是數組還是對象
        if (Array.isArray(value)) { // 如果是數組,就要將這個數組的原型指向 arrayMethods
 Object.setPrototypeOf(value, arrayMethods); this.observeArray(value); } else { this.walk(value); } } // 遍歷
 walk(value) { for (let key in value) { defineReactive(value, key); } } // 數組的特殊遍歷
 observeArray(arr) { for(let i = 0; i < arr.length; i++) { // 逐項進行 observe
 observe(arr[i]); } } }

array.js

import { def } from './utils'; const arrayPrototype = Array.prototype; // 以 Array.prototype 為原型創建 arrayMethods 對象
export const arrayMethods = Object.create(arrayPrototype); // 要被改寫的七個方法
const methodsNeedChange = [ 'push', 'pop', 'shift', 'unshift', 'sort', 'reverse', 'splice', ]; methodsNeedChange.forEach(item => { // 備份原來的方法,原有功能不能被剝奪
  const original = arrayPrototype[item]; // 定義新的方法
  def(arrayMethods, item, function() { // 恢復原來的功能,this代表調用該方法的數組,arguments就是push的內容
    const result = original.apply(this, arguments); // 將類數組轉換為數組
    const args = [...arguments]; // 把這個數組身上的__ob__取出來,__ob__已經被添加了
    // 為什么已經被添加了?
    // 因為數組肯定不是最高層,比如 obj.g 屬性是數組,obj不能是數組,
    // 第一次遍歷 obj 這個對象的第一層的時候,已經給 g 屬性添加了 __ob__屬性。
    const ob = this.__ob__; // 有三種方法 push、unshift、splice 能夠插入新項,現在要把插入的新項也變為 observe 的
    let inserted = []; switch(item) { case 'push': case 'unshift': // push(新項) unshift(插入的新項)
        inserted = arguments; break; case 'splice': // slice(下標,數量,插入的新項)
        inserted = args.slice(2); break; } // 讓插入的新項也變成響應的
    if (inserted) { ob.observeArray(inserted); } console.log('啦啦啦'); return result; }, false); });

defineReactive.js

import observe from './observe'; export default function defineReactive(data, key, val) { if (arguments.length == 2) { val = data[key]; } // 子元素要進行 observe, 至此形成了遞歸,
    // 這個遞歸不是函數自己調用自己
    let childOb = observe(val); Object.defineProperty(data, key, { // 可枚舉
        emuerable: true, // 可以被配置,比如可以被 delete
        configurable: true, get() { console.log(`正在訪問${key}屬性`, val); return val; }, set(newValue) { console.log(`正在改變${key}屬性`, newValue); if (val === newValue) { return }; val = newValue; // 當設置了新值,新值也要 observe
            childOb = observe(newValue); } }) }

utils.js

export const def = function(obj, key, value, emurable) { Object.defineProperty(obj, key, { value, emurable, writable: true, configurable: true }) }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM