工作生活

VUEX模块化

2019-06-30  本文已影响0人  RadishHuang

vuex模块化官方文档

项目github地址

vuex的官网上,关于模块化和热重载的文档都是蛮详细的,这边也就不一一的搬砖,没啥意义。这边着重是介绍下项目中是如何使用以及模块之间的调用和模块如何引入。

文件结构

const state = {
    JokeList: []
}

const getters = {
    JokeList(state) {
        return state.JokeList;
    }
}

const actions = {
    async getJoke({ commit }) {
        const result = await modal.fetchJoke();
        if (result.code == 200 && result.result.length) {
            commit('setJoke', result.result);
        }
    },
}
const mutations = {
    setJoke(state, params) {
        state.JokeList = params;
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}
import Vue from 'vue';
import Vuex from 'vuex';
import getters from './getters';
import actions from './actions';
import mutations from './mutations';
import defaultState from './state';
import home from './module/home';
import detail from './module/detail';
Vue.use(Vuex);
const isDev = process.env.NODE_ENV === 'development'
const store = new Vuex.Store({
        strict: isDev,
        state: defaultState,
        mutations,
        getters,
        actions,
        modules: {
            home,
            detail
        }
    })


<script>

import { mapActions, mapState } from 'vuex';

export default {
    mounted () {
        this.getJoke();
    },
    methods: {
        ...mapActions({
            getJoke: 'home/getJoke',
            getMain: 'getMain',
        }),
    },
    computed: {
        ...mapState({
            JokeList: state => state.home.JokeList,
             mainState: state => state.mainState
        }),
    }
}
</script>
const actions = {
    test1({ commit, dispatch }, params) {
        console.log('i am test1', params);
        dispatch('test2', params);
    },
    test2({ commit }, param) {
        console.log('i am test2', param);
    }
}
const actions = {
    getJokeDetail({ commit }, params) {

        //dispatch('setLoading', { root: true })
        commit(SET_LOADING, true, { root: true });
    },
}
const actions = {
    getJokeDetail({ commit }, params) {
        //dispatch('detail/setLoading')
        commit('detail/setLoading');
    },
}

总结

vuex的模块化能让我们按照不同的业务,解耦出vuex的不同模块出来。模块之间的相互调用只需要将namespaced设置为true,就可以实现模块名称+方法名称的方法之间调用。使得我们更方便的管理不同模块之间的状态。

上一篇下一篇

猜你喜欢

热点阅读