57

I have the below getter:

withEarmarks: state => {
    var count = 0;
    for (let l of state.laptops) {
        if (l.earmarks.length > 0) {
            count++;
        }
    }
  return count;
}

And in a component, this computed property derived from that getter:

    withEarmarks() { return this.$store.getters.withEarmarks; },

The value returned is correct, until I change an element within the laptops array, and then the getter doesn't update.

daninthemix
  • 2,252
  • 6
  • 19
  • 37

2 Answers2

121

In your case state.laptops.earmarks is an array, and you are manipulating it by its array index state.laptops[index]. Vue is unable to react to mutations on state arrays (by index). The documentation provides 2 workarounds for this:

// 1. use purpose built vue method:
Vue.set(state.laptops, index, laptop)

// 2. splice the value in at an index:
state.laptops.splice(index, 1, laptop)

Although it is documented, I'm thinking a giant neon glowing sign on that page that says "You will waste hours of productivity if you don't know this" would be a nice addition.

You can read more about this "caveat" here: https://vuejs.org/v2/guide/list.html#Caveats

jpschroeder
  • 5,373
  • 2
  • 28
  • 33
0

Apart from the Reactivity issue and Vue caveat, there could be another reason, You've introduced the local variable counter in computed function, You can try using reduce function as given.

withEarmarks: state => {
    return state.laptops.reduce((acc, item) => {
        if(item.earmarks.length > 0){
            acc++;
        }
        return acc;
    }, 0);
}

consider the @jpschroeder's answer in addition of this answer.

Kiran Maniya
  • 5,637
  • 4
  • 34
  • 53