vuex模块化结构目录
1>store>index.js
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.js
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.js
export const perpage = state => { return state.te2Sys + 'c4'; };
3>store>system>mutations.js
import * as types from './mutation-types'; export default { [types.SYSTEM_LOG_ID_QUERY](state, res) { state.te2Sys = state + res; } };
4>store>system>mutation-types.js
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的
store>api>actions.js
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页面开始调用,也就是所谓的执行入口
<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全家桶的内部调用形式,第二个是外部传来的参数
在方法里面直接演示了
state, dispatch, commit, getters这四种调用的形式,其中需要注意一点的是dispatch里面的{ root: true },不加就会报错
错误原因是你可以理解为deep这种深度监听,它会寻找到这个模块下的根目录,然后就会调用
api/getTopUserList也就是api模块下的getTopUserList的actions的方法
想要具体了解,就看官网https://vuex.vuejs.org/zh/guide/modules.html
3>从system模块下进入到了api模块下的actions的getTopUserList
4>然后进入到了相同模块下的ajaxMethod