vuex模块化结构目录html
1>store>index.jsvue
import Vue from 'vue'; import Vuex from 'vuex'; import state from './state'; import mutations from './mutation'; import api from './api'; import system from './system'; Vue.use(Vuex); export default new Vuex.Store({ state, mutations, modules: { api: api, system: system } });
2>store>system>actions.jsajax
import * as types from './mutation-types'; export const topUserListAction = ({ state, dispatch, commit, getters }, params) => { let payload = { val: 99 }; console.log('我进来了params', params.data); commit(types.SYSTEM_LOG_ID_QUERY, params.data); console.log('我进来了5state', state); console.log('我进来了5state', getters.perpage); dispatch('api/getTopUserList', payload, { root: true }); };
2>store>system>getters.jsvuex
export const perpage = state => { return state.te2Sys + 'c4'; };
3>store>system>mutations.jsapi
import * as types from './mutation-types'; export default { [types.SYSTEM_LOG_ID_QUERY](state, res) { state.te2Sys = state + res; } };
4>store>system>mutation-types.jside
export const SYSTEM_LOG_ID_QUERY = 'SYSTEM_LOG_ID_QUERY';
5>store>system>index.js模块化
import * as actions from './actions'; import mutations from './mutations'; import * as getters from './getters'; const state = { te2Sys: 'c3' }; export default { namespaced: true, state, getters, actions, mutations };
6>store的api其余大体与system同样,主要是actions的ui
store>api>actions.jsthis
export const getTopUserList = ({ state, dispatch }, payload, root) => { console.log('我进来了2', payload); dispatch('api/ajaxMethod', { param: ['get', state.server + '/dispatch/order/findTop10Users', payload.param, payload] }, { root: true }); }; export const ajaxMethod = ({ state, dispatch }, data) => { console.log('我进来了7', data); };
7>vue页面开始调用,也就是所谓的执行入口spa
<script> import { mapGetters, mapActions } from 'vuex'; export default { components: {}, props: {}, data() { return {}; }, watch: {}, computed: {}, methods: { ...mapActions('system', ['topUserListAction']) }, created() {}, mounted() { console.log(this.$store); this.topUserListAction({ data: '我是人' }); } }; </script>
解析:
1>在vue中打印的
console.log(this.$store); 中,vuex的actions的值目前为如今这样,由于是模块化因此带上了相似api/后面跟的其中action暴露的方法名字,
并且调用的时候须要
...mapActions('system', ['topUserListAction'])
前面那一个必须是模块名,后面为模块名对应的方法名,若是2个action模块不同,那就再调一次,如
...mapActions('api', ['***'])
2>第一步执行以后,就先走到了store>system>actions.js的topUserListAction里面
能够看到第一组对象是vuex全家桶的内部调用形式,第二个是外部传来的参数
在方法里面直接演示了