Vue(四)

477 阅读2分钟

Vuex 中的四个map函数

对于这四个函数的理解:能使代码更加简洁,而且不用重复写

mapState

函数最终返回一个对象,适用于Vue 的computed中。
    // namespace 可以不传,默认为空  或者传入 module 对应的键名,从而获取指定的module state值
    // 并且 查找的module 必须 namespaced 为true
    // state [] || {} 可以为数组或者对象,
    var mapState = normalizeNamespace(function (namespace, states) {
        var res = {};
        // 对象重新组装
        normalizeMap(states).forEach(function (ref) {
            var key = ref.key; // computed 对应的名称
            var val = ref.val; // 函数 或者 state 对应的键值

            res[key] = function mappedState() {
                var state = this.$store.state;
                var getters = this.$store.getters;
                // 从指定的module 中获取
                if (namespace) {
                    var module = getModuleByNamespace(this.$store, 'mapState', namespace);
                    if (!module) {
                        return
                    }
                    state = module.context.state;
                    getters = module.context.getters;
                }
                // 函数回调,或者直接返回对象
                return typeof val === 'function'
                    ? val.call(this, state, getters)
                    : state[val]
            };
            // mark vuex getter for devtools
            res[key].vuex = true;
        });
        return res
    });

mapGetters

函数最终返回一个对象,适用于Vue 的computed中。
     // namespace 可以不传,默认为空  或者传入 module 对应的键名,从而获取指定的module state值
    // 并且 查找的module 必须 namespaced 为true
    // state [] || {} 可以为数组或者对象,
     var mapGetters = normalizeNamespace(function (namespace, getters) {
        var res = {};
        normalizeMap(getters).forEach(function (ref) {
            var key = ref.key; // computed 名称
            var val = ref.val; // getters 名称

            // The namespace has been mutated by normalizeNamespace
            val = namespace + val; // 拼接
            res[key] = function mappedGetter() {
                // 先进行判断
                if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
                    return
                }
                // 判断是否真的存在
                if (!(val in this.$store.getters)) {
                    console.error(("[vuex] unknown getter: " + val));
                    return
                }
                // 返回一个getters 
                return this.$store.getters[val]
            };
            // mark vuex getter for devtools
            res[key].vuex = true;
        });
        return res
    });

mapMutations

函数最终返回一个对象,适用于Vue 的methods中。
        // namespace 可以不传,默认为空  或者传入 module 对应的键名,从而获取指定的module state值
        // 并且 查找的module 必须 namespaced 为true
        // state [] || {} 可以为数组或者对象,
        var mapMutations = normalizeNamespace(function (namespace, mutations) {
        var res = {};
        normalizeMap(mutations).forEach(function (ref) {
            var key = ref.key;
            var val = ref.val;

            res[key] = function mappedMutation() {
                // 传入的参数 数组化
                var args = [], len = arguments.length;
                while (len--) args[len] = arguments[len];

                // Get the commit method from store
                // commit 事件 标记
                var commit = this.$store.commit;
                if (namespace) {
                    var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
                    if (!module) {
                        return
                    }
                    commit = module.context.commit;
                }
                return typeof val === 'function'
                    ? val.apply(this, [commit].concat(args)) // 函数中回调 commit 
                    : commit.apply(this.$store, [val].concat(args)) // 直接回调
            };
        });
        // 返回 函数
        return res
    });

mapActions

函数最终返回一个对象,适用于Vue 的methods中。
        // namespace 可以不传,默认为空  或者传入 module 对应的键名,从而获取指定的module state值
        // 并且 查找的module 必须 namespaced 为true
        // state [] || {} 可以为数组或者对象,
        var mapActions = normalizeNamespace(function (namespace, actions) {
        var res = {};
        normalizeMap(actions).forEach(function (ref) {
            var key = ref.key;
            var val = ref.val;

            res[key] = function mappedAction() {
                // 传入的参数 数组化
                var args = [], len = arguments.length;
                while (len--) args[len] = arguments[len];

                // get dispatch function from store
                var dispatch = this.$store.dispatch;
                // 判断 是否存在module
                if (namespace) {
                    var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
                    if (!module) {
                        return
                    }
                    dispatch = module.context.dispatch;
                }
                return typeof val === 'function'
                    ? val.apply(this, [dispatch].concat(args)) // 函数中回调 dispatch 
                    : dispatch.apply(this.$store, [val].concat(args)) // 直接回调
            };
        });
        return res
    });

举个列子

    let module = {
    state: {
        person: {
            name: '天罗',
            age: 23,
            sex: 'boy',
        },
        skill: {
            Vue: "熟悉Vue流程",
            Vuex: "熟练使用",
            VueRouter: "熟练使用",
            javaScirpt: "熟练底层知识",
            HTML: "用用够",
            Css: "画画够用"
        }
    },
    getters: {
        getPerson: function (state) {
            return state.person;
        },
        getSkillPoint: function (state) {
            return function (type) {
                return state.skill[type]
            }
        }
    },
    actions: {
        modifyPerson: function (obj, payload, cb) {
            this.commit('modifyPerson', payload);
            cb();
        }
    },
    mutations: {
        /**
         *
         * @param state state
         * @param payload 外界传入的参数
         */
        modifyPerson: function (state, payload) {
            for (let key in payload) {
                if ((key in state.person)) {
                    state.person[key] = payload.key;
                }
            }
        }
    }
}
Vue.use(Vuex);
let mapState = Vuex.mapState;
let mapGetters = Vuex.mapGetters;
let mapActions = Vuex.mapActions;
let mapMutations = Vuex.mapMutations;
let store = new Vuex.store(module);

let e = new Vue({
    el: "#app",
    computed: {
        // 就直接调用 user skill
        ...mapState({
            user: "person",
            skill: function (state, getters) {
                return state.skill
            }
        }),
        // 就直接调用 Person Skill
        ...mapGetters({
            Person: "getPerson",
            Skill: "getSkillPoint"
        })
    },
    methods: {
        // 就直接调用 modifyPersonMutation
        ...mapMutations({
            modifyPersonMutation: function (commit, a, b) {
                // 调用commit
            }
        }),
        // 就直接调用 modifyPersonAction
        ...mapActions({
            // 直接调用了 modifyPerson函数
            // 字符串对应的 事件名
            modifyPersonAction: "modifyPerson"
        })
    },
})
初始见到map的时候配合着ES6语法,有一种畏惧感,走进它的内部,细致的挖掘,也不过如此,更加透彻的了解了它。在使用过程中更加自信,写出更优质的代码。