vuex access getters from actions
- Import the
mapGetters
helper function from 'vuex' in your component file.
import { mapGetters } from 'vuex';
- Add the
...mapGetters
spread operator in thecomputed
property of the component, specifying the getters you want to access.
computed: {
...mapGetters(['getterName1', 'getterName2']),
},
- Within your action method, access the getters using
context.getters
and store the result in a variable.
actions: {
someAction(context) {
const result1 = context.getters.getterName1;
const result2 = context.getters.getterName2;
// Perform actions with the getter results
},
},
- Alternatively, use ES6 destructuring to directly extract the getters from the
context
parameter.
actions: {
someAction({ getters }) {
const result1 = getters.getterName1;
const result2 = getters.getterName2;
// Perform actions with the getter results
},
},
Note: Replace 'getterName1' and 'getterName2' with the actual names of the getters you want to access in both the mapGetters
and action sections.