vue computed 原理


vue computed 主要依靠數據依賴來更新,這里不展示computed源代碼,只展示核心思想。

computed: {
  a(){
     return this.b ++
   }  
}
data:{
  b: 1  
}

vue中如果b變化,a也會變化。這兒為了簡單,不在展示computed.a的set跟get

1、data中的數據需要使用es5中的 Object.defineProperty 設置set,get屬性。

2、在運行computed.a()函數的時候,需要建立數據依賴,搜集。

    // 做一個構造函數A,作用是對data添加特性方法(set,get)
    class A {
      constructor(data, computed) {
        this.defineProperty(data, 'a',data.a) // 對data中的屬性‘a’添加特性方法
        this.collect =  computed.computA, // computed中的函數,記錄下來
          
        computed.computA() // 運行此函數,會對data.a 進行取值,觸發data.a的get函數,建立依賴
      }

      defineProperty(obj, key, val) { // 使用函數封裝 添加特性方法
        const collect = [] 
        Object.defineProperty(obj, key, {
          get:()=> {                    // 當取值 data.a 時會觸發get函數
            if (this.collect && !collect.some(it => it === this.collect)) {
              collect.push(this.collect)  // 如果探測到有需要運行的compueted函數,搜集起來。
            }
            return val
          },
          set:value => {
            val = value
            collect.forEach(it => it())  // 如果data.a = 2 則運行set特性函數,此時,那些搜集起來的computed函數都運行
          }
        })
      }
    }



const computed
= { computA() {
     let result = data.a +1
     console.log(result)
return result } } const data = { a: 1 } // 測試 new A(data, computed) // 2 data.a++ // 3 data.a = 6 //7

 


免責聲明!

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



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