Vuex $store properties not reactive when using computed property

babbaggeii picture babbaggeii · Jan 25, 2017 · Viewed 20k times · Source

I have a Vuex store, which I'm injecting into my instance:

import store from '../store';

const mainNav = new Vue({
  el: '#main-nav',
  store,
  components: { NavComponent }
});

And I'm creating a computed property from that store in the component:

computed: {
  isWide() {
    return this.$store.state.nav.type === 'wide';
  }
}

This does create the this.isWide property for the template on component initialization, but when the store value is updated, the component doesn't register this - the old value is still on the template.

What am I doing wrong here?

Answer

CodinCat picture CodinCat · Jan 25, 2017

Your code should work if you setup everything correctly: http://codepen.io/CodinCat/pen/RKZeZe?editors=1010

A very common mistake is that you didn't give your state initial data.

You should declare the state shape explicitly, so instead of

state: {}

// or

state: {
  nav: {}
}

do this:

state: {
  nav: {
    type: '...'
  },
  ...
}

or the properties will not be reactive, like this example: http://codepen.io/CodinCat/pen/ggxBEV?editors=1010

And make sure you did update the state, maybe the problem is just you didn't update the state correctly as you expected.