首先上一個思惟導圖便於理解:vue
下面是原代碼,其實原代碼很簡單易懂的(來自網絡):react
function set(target: Array<any> | Object, key: any, val: any): any { // isUndef 是判斷 target 是否是等於 undefined 或者 null 。 //isPrimitive 是判斷 target 的數據類型是否是 string、number、symbol、boolean 中的一種 if (process.env.NODE_ENV !== 'production' && (isUndef(target) || isPrimitive(target)) ) { warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`) } // 數組的處理 if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key) target.splice(key, 1, val) return val } // 對象,而且該屬性原來已存在於對象中,則直接更新 if (key in target && !(key in Object.prototype)) { target[key] = val return val } // vue給響應式對象(好比 data 裏定義的對象)都加了一個 __ob__ 屬性, // 若是一個對象有這個 __ob__ 屬性,那麼就說明這個對象是響應式對象,咱們修改對象已有屬性的時候就會觸發頁面渲染。 // 非 data 裏定義的就不是響應式對象。 const ob = (target: any).__ob__ if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ) return val } // 不是響應式對象 if (!ob) { target[key] = val return val } // 是響應式對象,進行依賴收集 defineReactive(ob.value, key, val) // 觸發更新視圖 ob.dep.notify() return val }