Giter VIP home page Giter VIP logo

Comments (1)

sl1673495 avatar sl1673495 commented on June 18, 2024

关于计算属性的缓存,在网上看过挺多篇文章并没有讲的很清楚,今天我们从源码来分析一下它这个缓存到底是怎么做的。

首先我们知道 当依赖值a改变的时候 a会触发dep.notify 这个dep里收集了计算属性sum的watcher 会触发这个watcher的update, 我们来看update里关键的节选

update () {
    if (this.computed) {
      ....
        this.getAndInvoke(() => {
          this.dep.notify()
        })
    }
  }

我们会把触发渲染watcher更新的this.dep.notify包裹在 this.getAndInvoke内部,那我们来看看那 this.getAndInvoke做了什么

getAndInvoke (cb: Function) {
    const value = this.get()
    if (
      value !== this.value ||
      isObject(value) ||
      this.deep
    ) {
      const oldValue = this.value
      this.value = value
      this.dirty = false
      if (this.user) {
        try {
          cb.call(this.vm, value, oldValue)
        } catch (e) {
          handleError(e, this.vm, `callback for watcher "${this.expression}"`)
        }
      } else {
        cb.call(this.vm, value, oldValue)
      }
    }
  }

首先会调用this.get() ,获取到当前计算属性最新的值,然后去和上次计算属性的值进行比较,只有在值发生变化以后才回去执行接下来的回调, 才会去触发视图的重新渲染,这也就是为什么说新版的计算属性是更多计算,更少的更新。

from blogs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.