A
A
Alexander Buki2019-07-23 17:36:09
JavaScript
Alexander Buki, 2019-07-23 17:36:09

How to update computed property in VUE when Array element changes?

Good afternoon.
There is a computed prop- filterResultSelectionIds:

filterResultSelectionIds() {
            let filterSelection = [];
            this.filterResultSelection.forEach((group) => {
                filterSelection.push(group);
            });
            filterSelection = [].concat(...filterSelection);
            return filterSelection.map(el => el.id);
        }

By clicking on the checkbox, the element in the group (group) changes, the filterResultSelectionIds array itself remains unchanged.
How can I make the computed prop update anyway?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
floydback, 2019-07-24
@alexbuki

Computed properties always cache the value and update the cache only when the reactive data has changed. It does not update the array, unless its length has changed. So changing an array element will not trigger a computed property update. You can use watcher with option deep: true

O
ozeddev, 2021-10-11
@ozeddev

I'll leave this here for those who are looking for an answer to a similar question.
In such situations, when we want to "update" the computed property when a non-reactive event occurs, it is sometimes very convenient to set a counter variable in data. When such an event occurs, we simply increase the counter.
In our target computed property, we use this variable as we like, for example like this:

data() {
    return {
      changed: 0,
      myArray: []
    }
},
computed: {
    isArrayChanged() {
      let hook = this.changed;
      return (myArray)
    }
},
methods: {
    myArrayNewLenght(data) {
      myArray.length = data; //
      this.changed++;
    }
}

Even though this array length change is non-reactive, we have changed our reactive changed variable, which is used in our computed property, which means the property will be updated.

S
spike__x, 2017-11-06
@verdex

So?
https://regex101.com/r/MmHDrX/1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question