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
原文地址:https://www.cnblogs.com/gsgs/p/8794573.html