46

I have this Vue.js code:

new Vue({
  data:{
         myValue:'x',
         myOtherValue:'y'
  },
  computed: {
       myComputed: myFunction(){
          return this['my' + 'Value']
       }
  }
})

As you can see the computed property will be cached and it is depended only on data.myValue. My question is how Vue.js caching system knows that run the computed function again only if myValue is changed?

If I change the myOtherValue variable, the myComputed function will use the cache, and will not be run again will I call it.

I thought about several ways how it is possible. But how Vuejs doing that? I have read this article: https://v2.vuejs.org/v2/guide/computed.html and found no answer.

And what happen in this code, what it will be depeneded on?

const flag=2
new Vue({
  data:{
         myValue:'x',
         myOtherValue:'y'
  },
  computed: {
       myComputed: myFunction(){
          if (flag==1){
              return this['my' + 'Value']
          }
          else
              return this['my' + 'Other' + 'Value']
       }
  }
})

Bonus: I will appreciate I link to the relevant function in the VueJS code: https://github.com/vuejs/vue

2

3 Answers 3

48

I will address only the specific question how does vue.js know which dependencies affect which computed property?

The simple answer is that each time vue evaluates a computed property it creates a map of all the reactive properties that were accessed in the span of that call. The next time any of these reactive properties change they will trigger a reevaluation of the computed property.

If during the most recent evaluation of a computed property, one of its reactive dependencies is never reached (maybe because it is within the non-traveled path of an if/else construct), subsequent changes to that reactive property will not trigger a reevaluation of the computed property.

Observe this behavior by modifying the two reactive properties in this fiddle (by simply typing in their corresponding input boxes). A few things to note:

  • the called computed property is evaluated once on document load (it's triggered because it's rendered in the template).
  • because the path is set to 1 the reactive property that will be mapped as a dependency is val1. As a result it will be the only one that can trigger a reevaluation of called when it changes. The value of val2 can also change but will not have the same effect on called, even though it's clearly present in the function.
  • When you click on the "Change Path" button, path is toggled from 1 to 2.
  • right after the path switch, note that a change to val1 will affect called only once more. Because path has been set to 2 prior to that last reevaluation, val1 will not be reachable and will not be mapped as a dependency of called any longer. Subsequent changes to its value won't trigger a reevaluation of called from that point on. But then val2 has now been mapped as a dependency of called and changes to it trigger the reevaluation the same way they did for val1 earlier. It will be so until the next path toggle from 2 back to 1.

Here's the code.

let path=1
let count=0
const vm=new Vue({
  el:"#app",
  data:{
         val1:null,
         val2:null,
  },
  computed: {
       called: function(){

            if (path==1){
              this.val1
            }
            if (path==2){
                this.val2
            }
            return "I was just called "+ ++count +" times"
       }
  },
  methods: {
    changePath(){
        path = path==2 ? 1 : 2
    }
  }
})

and corresponding template

<div id="app">
  <input v-model="val1"/> {{val1}}
  <br>
  <input v-model="val2"/> {{val2}}
  <br>
  <button @click="changePath">change path</button>
  <br>
  {{ called }}
</div>
7
  • 7
    I feel like this should be the accepted answer. I appreciate CodinCat sharing a link to the original code but I'd prefer someone giving a gist of the way it works. Dec 3, 2018 at 19:06
  • 1
    This clearly explain how the "wrong counting" happens. What's your suggestion on how to avoid it?
    – Yiping
    Dec 9, 2019 at 7:42
  • 1
    @Yiping Seems to me like the solution is to make sure computed functions always contain dependent properties at the top level. In the above example, path should not be in the global scope (outside of Vue's realm of responsibility) but should instead be in data, where setters and getters are utilized to monitor its state. If data.path changes, it will trigger a re-run of called() where it will then get see the change in this.val2. If this.val2 were at the top level of the function (not inside the if) called() would have been executed if it changed. Dec 22, 2019 at 20:06
  • 2
    @Yiping Essentially, if you want a computed function to register specific dependencies, you need to make sure that they're accessed every time the computed function is called. As a simple hack you could just list them at the beginning of the function. this.val1; this.val2 at the top would make a change to either of them re-trigger the call to the computed function. Dec 22, 2019 at 20:11
  • 1
    More explanation how it works here, pointed out by this forum post, which links to here.
    – mirabilos
    Apr 21, 2020 at 19:12
21

It's the reactivity system of Vue.js, not a caching system.

The data in a component will be convert to getters and setters. When you access a value via a getter, the getter will add it to the dependencies, and when you modify the value via a setter, the setter will notify everyone who depends on the value.

Here is the source code, all the magic happens in this function: https://github.com/vuejs/vue/blob/dev/src/core/observer/index.js#L131

5
  • 2
    If this is the mechanism. It will be buggy. In the second example. If I change the flag value to 1, I will get the caching answer when (flag==2), instead of new answer. Jan 9, 2017 at 8:24
  • 2
    Yes, this is an interesting question. because flag is not reactive, so the myComputed will not aware about the change of flag. Here is the demonstration: codepen.io/CodinCat/pen/rjOjjQ flag will be updated after 1 sec, but the computed property will not react to the flag
    – CodinCat
    Jan 9, 2017 at 8:51
  • 2
    myComputed will only be updated after 10 secs, because you touch myOtherValue. If you change the interval to this.myValue += 1, myComputed will never be updated, because myValue is not a dependency of myComputed
    – CodinCat
    Jan 9, 2017 at 8:52
  • 3
    So the correct way is to add flag to the data of that component, then it will be converted to a reactive property, and become a dependency of myComputed, then everything should work perfectly.
    – CodinCat
    Jan 9, 2017 at 8:57
  • 2
    Here is another working example: codepen.io/CodinCat/pen/vgNgQy in case you want to have a variable outside of the component. It must be an object, when you feed that object to the data, it will be converted to a reactive property, so myComputed can collect it as dependency correctly
    – CodinCat
    Jan 9, 2017 at 9:05
2

From the docs it reads that: Computed properties are cached, and only re-computed on reactive dependency changes. However the following fiddle shows something a bit different.

  1. https://jsfiddle.net/z11fe07p/267/

From the fiddle if you set the flag to 2, the computed property will be re-evaluated and executed if you change myOtherValue, however this will not happen if the flag is set to 1. I think it keeps track of your if conditions.

In the docs usually you can find links to the relevant source code. Here is the code for computed properties:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.