Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed property not updating from Vuex store object

Tags:

vue.js

vuex

I have a bunch of class binding statements:

:class="{active: isActive('status', status.id)}"

Here's the method referred to above:

isActive: function (param, value) {
    if (!this.activeFilters.hasOwnProperty(param) && value === 'all' && param !== 'type') {
        return true;
    }
...etc
}

...and the computed property the method is looking at:

activeFilters() {
    return this.$store.state.activeFilters;
},

Which is in the Vuex state.

The problem is, these properties aren't updating when one of the dropdowns with the above class binding is clicked on. If I navigate to another route and then back, the active class has been applied just fine. Can I force the computed property to recompute so the class is applied immediately?

I understand that adding properties won't trigger reactivity, but according to this, if I replace the object with a fresh one, reactivity should be maintained. Well here's what I'm doing:

state.activeFilters = query;

...replacing the object. I am stumped.

like image 646
daninthemix Avatar asked Nov 09 '16 18:11

daninthemix


1 Answers

Due to limitations in JavaScript, there are types of changes that Vue cannot detect with arrays and objects. You can read more about it here: https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

One simple solution is creating a method out of your computed property:

Before:

<Grid v-for="i in items" :items="items" />

<script>
  export default Vue.extend({
    .
    .
    .
    computed: {
      items() {
        return this.storedItems
      },
    }
  }
</script>

After:

<Grid v-for="i in items" :items="items" />

<script>
  export default Vue.extend({
    .
    .
    .
    methods: {
      items() {
        return this.storedItems
      },
    }
  }
</script>
like image 65
leonheess Avatar answered Nov 09 '22 22:11

leonheess