vue-状态管理与Vuex

### 状态管理与Vuex        
跨组件共享数据的需求;
### 配置vuex
    npm install --save vuex

    修改main.js
        import Vuex from 'vuex';
        Vue.use(Vuex);
        const store = new Vuex.Store({
            <!-- vuex的配置 -->
        })


        // 创建Vue根实例
        new Vue({
            el: '#app',
            router: router,
            store: store, // 使用vuex
            render: h => h(App)
        })


        mutations和actions用法:
        const store = new Vuex.Store({
            state: {
                count: 0
            },
            mutations: {
                increment (state, n = 1) {
                    state.count += n;
                }
            },
            actions: {
                increment (context) {
                    context.commit('increment')
                }
            }
        })


        vue页面使用:
        computed: {
            count() {
                return this.$store.state.count;
            }
        },
        methods: {
            handleActionIncrement() {
                this.$store.dispatch('increment');
            }
        }


        总结:actions主要是实现异步赋值操作(不做异步,也就没必要在actions中中转一次操作)


        actions实现异步操作例子:
        const store = new Vuex.Store({
            state: {
                count: 0
            },
            mutations: {
                increment (state, n = 1) {
                    state.count += 1;
                }
            },
            actions: {
                asyncIncrement (context) {
                    return new Promise (resolve => {
                        setTimeout(() => {
                            context.commit('increment');
                            resolve();
                        },1000)
                    });
                }
            }
        })


        // index.vue代码
        handleAsyncIncrement() {
            this.$store.dispatch('asyncIncrement').then(() => {
                console.log(this.$store.state.count); // 1
            })
        }
### vuex使用modules分割模块
作用:将store分割不同的模块,项目足够大时,方便管理
实例:
const moduleA = {
    state: {...},
    mutations: {...},
    actions: {...},
    getters: {...}
}


const moduleB = {
    state: {...},
    mutatios: {...},
    actions: {...}
} 


const store = new Vuex.Store({
    modules: {
        a: moduleA,
        b: moduleB
    }
})


store.state.a // modulesA的状态
store.state.b // modulesB的状态


注意:module的mutation和getter接收的第一个参数state是当前模块的状态。
在actions和getters中,还可以接收一个参数rootState,来访问根节点的状态。
const moduleA = {
    state: {
        count: 0,
    },
    getters: {
        sumCount (state, getters, rootSate){
            return state.count + rootState.count;
        }
    }
}
原文地址:https://www.cnblogs.com/fdxjava/p/14803166.html