首页 > 其他 > 详细

vue computed 原理

时间:2018-04-11 14:32:25      阅读:212      评论:0      收藏:0      [点我收藏+]

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.push(this.collect)  // 如果探测到有需要运行的compueted函数,搜集起来。
            }
            return val
          },
          set(value) {
            val = value
            collect.forEach(it => it())  // 如果data.a = 2 则运行set特性函数,此时,那些搜集起来的computed函数都运行
          }
        })
      }
    }



const computed
= { computA() { return data.a + 1 } } const data = { a: 1 } // 测试 new A(data, computed) computed.computA() // 2 data.a++ computed.computA() // 3

 

vue computed 原理

原文:https://www.cnblogs.com/gsgs/p/8794573.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!