快速解决方案
Vuex助手(如mapMutations
等)返回一个填充了函数的对象,该函数假定this.$store
是Vuex存储.
store 服务
如果需要在vanilla JS中使用store,并且不想在任何地方公开store模块,那么可以定义一个服务模块.
import { mapActions } from 'vuex';
import $store from '@/store';
/**
* Simple mapping of the Vuex store UI module.
* @module services/ui
* @property {Function} pushMessage
*/
export default Object.assign({
$store,
}, mapActions('ui', ['pushMessage']));
现在,使用它就像导入服务模块一样简单.
import ui from './services/ui';
// triggers the `pushAction` on the ui namespaced store module
ui.pushMessage({ content: 'whatever' });
要在Vue组件上计算默认值和方法,可以创建一个简单的mixin来导入特定组件.
import { mapState, mapMutations } from 'vuex';
export default {
computed : mapState(['isLoggedIn']),
methods: mapMutations(['logout'])
}
然后,在组件中使用mixin.
<script>
import mixin from './mixin';
export default {
mixins: [mixin],
data() {/* ... */},
// etc.
}
</script>
如果您真的希望每个组件都有这个默认的mixin,而不必显式地定义它,请使用全局mixin.
import Vue from 'vue';
import { mapState, mapMutations } from 'vuex';
export const mixin = {
computed : mapState(['isLoggedIn']),
methods: mapMutations(['logout'])
};
Vue.mixin(mixin);
Personally, as a standard, I never map the state or mutations.
I only map getters and actions so my components don't need to know the state structure and that an action is async or not. I see getters and actions as the public API of a Vuex store (or any similar store, like Redux).
I also only map the relevant data. Components responsibility is to interact with the user of the app, displaying and handling events and nothing more. If all your components need the 100 object, maybe they're doing too much and that logic should probably be moved elsewhere, like in an action.
See more on 100