Cinta
Cinta

Reputation: 485

Vuex mapstate undefinded

I'm having trouble using the Vuex mapstate. While testing writing this.$store.state.count but I'm trying to shorten the name down to this.count. My vue project is deeply nested, so I'm trying to make the variables short and trying to avoid using "computed" and other functions inside every component.

my code

const store = new Vuex.Store({
    state: {
        count: 43,
    }

});
import { mapState } from 'vuex';


let app = new Vue({
    el: '#app',
    router: new VueRouter(routes),
    store,
    computed: mapState([
        'count'
    ]),
    data: {
        current_path: '/dashboard',
    },
});

I've also tried:

computed: mapState({
    // arrow functions can make the code very succinct!
    count: state => state.count,

    // passing the string value 'count' is same as `state => state.count`
    countAlias: 'count',

    // to access local state with `this`, a normal function must be used
    countPlusLocalState (state) {
      return state.count;
    }
  })

But in my component: when I use this.count or {{count}} (or countAlias, countPlusLocalState etc) in the html, it returns null/undefined. It only works with the full reference: this.$store.state.count.

What am I missing?

Upvotes: 0

Views: 168

Answers (1)

D Malan
D Malan

Reputation: 11464

You can use a global mixin like this:

Vue.mixin({
    computed: mapState([
        'count'
    ]),
})

Upvotes: 1

Related Questions