Mapping helpers

Vuex provides a few helper functions to add state, getters, mutations, and actions. Since we should only use getters and actions in our components to help separate the state and related logic from the components, we will only use mapGetters and mapActions.

These functions generate appropriate computed properties and methods to the components that rely on the corresponding getters and actions from the store, so you don't have to type this.$store.getters and this.$store.dispatch each time. The argument is either:

  • An array of types that are mapped with the same name as? the component
  • An object, whose keys are the aliases on the component and the value are the types

For example, the following code using the array syntax:

mapGetters(['a', 'b'])

Is equivalent to this in the component:

{
a () { return this.$store.getters.a },
b () { return this.$store.getters.b },
}

And the following code using the object syntax:

mapGetters({ x: 'a', y: 'b' })

Is equivalent to this:

{
x () { return this.$store.getters.a },
y () { return this.$store.getters.b },
}

Let's refactor our AppMenu component to use those helpers:

  1. First import those in the component:
      import { mapGetters, mapActions } from 'vuex'
  1. Then, we can rewrite the component like this:
      export default {
computed: mapGetters([
'user',
'userPicture',
]),
methods: mapActions({
centerOnUser: 'login',
logout: 'logout',
}),
}

Now, the component will have two computed properties that return the corresponding store getters, and two methods that dispatch the 'login' and 'logout' action types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.124.244