Effective Solutions
The Vuex utility functions such as mapMutations
generate an object with functions that assume the presence of a Vuex store at this.$store
.
Utilizing Store Service
If you aim to access the store in pure JavaScript without exposing the module everywhere, creating a service module can be beneficial.
import { mapActions } from 'vuex';
import $store from '@/store';
/**
* Basic mapping of the Vuex store UI module.
* @module services/ui
* @property {Function} pushMessage
*/
export default Object.assign({
$store,
}, mapActions('ui', ['pushMessage']));
By importing the service module, utilizing it becomes straightforward.
import ui from './services/ui';
// triggers the `pushAction` on the ui namespaced store module
ui.pushMessage({ content: 'whatever' });
To establish default computed properties and methods on a Vue component, creating a simple mixin for specific components is a useful strategy.
import { mapState, mapMutations } from 'vuex';
export default {
computed : mapState(['isLoggedIn']),
methods: mapMutations(['logout'])
}
You can then apply the mixin in a particular component.
<script>
import mixin from './mixin';
export default {
mixins: [mixin],
data() {/* ... */},
// etc.
}
</script>
If there is a requirement for all components to inherit a default mixin without explicit declaration, employing a global mixin is recommended.
import Vue from 'vue';
import { mapState, mapMutations } from 'vuex';
export const mixin = {
computed : mapState(['isLoggedIn']),
methods: mapMutations(['logout'])
};
Vue.mixin(mixin);
Personally, I refrain from directly mapping the state or mutations.
I prefer mapping getters and actions only, allowing components to interact without detailed knowledge of the state structure or async nature of actions. Getters and actions serve as the public interface of a Vuex store (or similar stores like Redux).
I also advocate for mapping only pertinent data. Components should focus on user interaction, displaying information, and event handling exclusively. If multiple components rely on the same user
object, it may indicate excessive responsibilities and the need to refactor logic into actions.
For further insights, refer to Vue communication