raklos
raklos

Reputation: 28545

mapState on non-namespaced module

I have a module

export default {
  namespaced: false,
  state,
  actions,
  mutations,
  getters
};

In my component I have tried these:

 ...mapState(["user"]),
 ...mapState('auth',["user"]),

but neither of them work, instead I have to use this as a computed property:

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

Is it possible to use ...mapState?

Upvotes: 4

Views: 1948

Answers (1)

Adam Jagosz
Adam Jagosz

Reputation: 1594

mapGetters

The most efficient way with non-namespaced modules is to define a getter. The advantage is that you don't have to redefine it in every component you want to use the property in.

getters: {
  user: state => state.user,
}
...mapGetters([
  "user",
]),

This stands in oposition to some beliefs that you "shouldn't overuse getters", but it's a sad reality that this is one thing Vuex got wrong. Since non-namespaced modules share their namespace with the root state, their props should be available right away as well, but they aren't.

mapState

If you want to use mapState instead, I don't think nested destructuring syntax is any good for that:

...mapState({
  user: ({ auth: { user } }) => user,
}),

This is not readable at all. This doesn't make your code any shorter, as you need to repeat the prop name anyway. This is the way to go:

...mapState({
  user: state => state.auth.user,
}),

Upvotes: 2

Related Questions