Vuex状态管理之模块化(精华总结)

Vuex.store中有一个modules属性:官方api文档:https://vuex.vuejs.org/zh/api/#modules

第一步:创建对应的模块化状态对象,并开启命名空间属性:namespaced: true,(这里最关键,如果不开启命名空间属性,则为全局模块化)

第二步:全局状态对象store绑定computed计算属性的快捷方式(开启了命名空间,Vuex中的map映射方法第一个参数必须是命名空间,只有是全局状态下,命名空间才可以省略!)

看一个完整的案例吧:

第一步.store.js模块化主文件:

import Vue from "vue";
import Vuex from "vuex";
import Users from "./store/user/index.js";

Vue.use( Vuex );

export default new Vuex.Store( {
    //模块化属性配置
    modules: {
        user: Users
    }
} );

 第二步、./store/user/index.js 子模块的路径主文件index.js

import state from "./state";
import getters from "./getters";
import mutations from "./mutations";
import actions from "./actions";


export default {
    //开启命名空间属性,如果不开启则为全局状态   
    namespaced: true,
    state: state,
    getters: getters,
    mutations: mutations,
    actions: actions

};

第三步:分别导入./store/user/下的对应的其他js文件    "./state.js"; "./getters.js"; "./mutations.js"; "./actions.js";

//state.js
export default {
    num: 5
};
//getters.js文件
export default {
    getNum: ( state ) => {

        return ( id ) => {
            return state.num + id;
        };
    },
    getNum1: ( state ) => {
        return state.num;
    }
};
//mutations.js文件

export default {
    add: function ( state, n ) {
        state.num = state.num + n;
    }
};
//actions.js文件
export default {
    updateNum: ( context, n ) => {
        console.log( n );
        setInterval( () => {
            context.commit( "add", n );
        }, 1000 );

    },
};

猜你喜欢

转载自blog.csdn.net/weixin_43343144/article/details/86510979
今日推荐