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全家桶的內部調用形式,第二個是外部傳來的參數
在方法裏面直接演示了