Vuex之第五彈終彈之模塊化實踐項目運用

 

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全家桶的內部調用形式,第二個是外部傳來的參數

在方法裏面直接演示了

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
相關文章
相關標籤/搜索