vuex.js mapState normalizeNamespace函数 namespace参数为空

源码vue.js 681行

var mapState = normalizeNamespace(function (namespace, states) {
  console.log('namespace:', namespace); 
  var res = {};
  normalizeMap(states).forEach(function (ref) {
    var key = ref.key;
    var val = ref.val;

    res[key] = function mappedState () {
      var state = this.$store.state;
      var getters = this.$store.getters;
      if (namespace) { // 为空导致不能进入这个条件语句。拿不到自定义的modules
        console.log('namespace2:', 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
});

打印为空:
clipboard.png

我的项目代码:

clipboard.png
mutation_types.js

export const SHOW_ADD_DETAIL = 'SHOW_ADD_DETAIL'; 

store/modules/topics.js

import * as types from '../mutation_types';

let state = {
    showAddDetail: false // 房源专题新增、详情
};

const getters = {};

const actions = {};
const mutations = {
    // 改变详情、新增房源专题 显示状态
    [types.SHOW_ADD_DETAIL](state, val){
        console.log('state....:', state);// 调用SHOW_ADD_DETAIL时 state打印为undefined
        state.showAddDetail = val;
    }
};
export default {
    state,
    getters,
    actions,
    mutations
};

store/index.js

import Vue from 'vue';
import Vuex from 'vuex';

import actions from './actions';
import mutations from './mutations';
import * as getters from './getters';

import topics from './modules/topics';

Vue.use(Vuex);

const listener = store => {
    if (!sessionStorage) {
        return;
    }
    store.subscribe((mutation, state) => {
        sessionStorage.setItem('state', JSON.stringify(state));
    });
};

export default new Vuex.Store({
    state: {
        dict: {},
        permissions: {}
    },
    modules: {
        topics
    },
    mutations,
    actions,
    getters,
    plugins: [listener]
});

使用时:

import {mapState, mapMutations} from 'vuex';

export default {
    // 省略代码
    computed: {
        ...mapState(['dict', 'topics']),
        showDetailTopic() { // 显示隐藏:房源专题详情、新增
            console.log('this.$store:', this.$store);
            console.log('dict'); //正常
            console.log(''topics); // undefined
            return this.topics; // undefined
        }
    },
    methods: {
        ...mapMutations(['SHOW_ADD_DETAIL']),
        test(){
            SHOW_ADD_DETAIL(true); // topics.js 里 state打印为undefined
        }
        }
  }
阅读 4k
1 个回答

不知道想问什么。你本来就没传 namespace 进去。

图片描述

mapState 接受两个参数,第一个参数是 namespace, 你传入一个数组,认为你传入的 是 map, namespace 被当做 ''

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题