mapState
import { mapState } from 'vuex' export default { // ... computed:{ ...mapState({ // Arrow function can make the code simpler count: state => , // Pass the string parameter 'count' is equivalent to `state => ` countAlias: 'count', // In order to be able to use `this` to get local state, regular functions must be used countPlusLocalState (state) { return + } }) } }
When the defined attribute name is the same as the name in state, an array can be passed in.
//Define stateconst state={ count:1, } //Use helper functions in componentscomputed:{ ...mapState(['count']) }
mapGetters
computed:{ ...mapGetters({ // Map `` to `this.$` doneCount: 'doneTodosCount' }) }
When the attribute name is the same as defined in getters, an array can be passed in
computed:{ computed: { // Use the object expansion operator to mix getter into the computed object ...mapGetters([ 'doneTodosCount', 'anotherGetter', // ... ]) } }
Summarize:
- mapState and mapGetters are both computed for mapping
- After mapping in the component is completed, use this.map attribute name
mapMutations
methods:{ ...mapMutations({ add: 'increment' // Map `()` to `this.$('increment')` }) }
When the attribute name is the same as defined in mapMutatios, an array can be passed in
methods:{ ...mapMutations([ 'increment', // Map `()` to `this.$('increment')` // `mapMutations` also supports payloads: 'incrementBy' // Map `(amount)` to `this.$('incrementBy', amount)` ]), }
mapActios
mathods:{ ...mapActions({ add: 'increment' // Map `()` to `this.$('increment')` }) }
When the attribute name is the same as defined in mapActivos, an array can be passed in
methods:{ ...mapActions([ 'increment', // Map `()` to `this.$('increment')` // `mapActions` also supports payloads: 'incrementBy' // Map `(amount)` to `this.$('incrementBy', amount)` ]), }
Summarize
- mapMutations and mapActivos are mapped in methods
- Mapping becomes a method
Multiple modules
When not using helper functions,
this.$('app/addCount')
Using helper functions, the first parameter of the helper function gives the path to the namespace
computed: { ...mapState('some/nested/module', { a: state => , b: state => }) }, methods: { ...mapActions('some/nested/module', [ 'foo', // -> () 'bar' // -> () ]) }
Or use the createNamespacedHelpers function to create a namespace-based helper function
import { createNamespacedHelpers } from 'vuex' const { mapState, mapActions } = createNamespacedHelpers('some/nested/module') //Give path//The usage method is the same as beforeexport default { computed: { // Find in `some/nested/module` ...mapState({ a: state => , b: state => }) }, methods: { // Find in `some/nested/module` ...mapActions([ 'foo', 'bar' ]) } }
The above is the detailed content of how to use vuex helper functions. For more information about vuex helper functions, please pay attention to my other related articles!