vue.js - vuex 模块 appState 不适用于作为第一个参数传递的模块命名空间

标签 vue.js vuex vuex-modules

如果我尝试将命名空间作为第一个参数传递,按照文档的建议,我会得到“undefined”作为值(“test”在模块定义中设置)

...mapState('guest', {
    email: state => state.email,
}),

但如果我只是这样做而不将命名空间作为第一个参数,它就可以正常工作

...mapState({
    email: state => state.guest.email,
}),

我想使用快捷方式,根据文档,第一个示例应该可以工作......对吗?

https://vuex.vuejs.org/guide/modules.html#binding-helpers-with-namespace

这是我的模块定义:

const initialState = function(){
    let state = {
        email: null,
    };

    return state;
};    

export default {
    namespaced: true,
    state: initialState(),
    mutations: {
        fill(state, data) {
            Object.assign(state, data);
        },
        reset(state) {
            Object.assign(state, initialState());
        }
    },
    actions: {
    }
};

最佳答案

您的计算...mapState语法是正确的,因此问题可能出在填充突变的调用方式上。您是否为提交命名?

这是一个working example

唯一需要改变的是state:initialState应该是state:Object.assign({},initialState)

第一种方法将 state 设置为对 initialState 对象的引用,因此填充突变中的任何更改都会覆盖 initialState 的值,而重置突变不会有任何影响。

组件

export default {
  ...
  computed: {
    ...mapState("guest", {
      email: state => state.email
    })
  },
  mounted() {

    // Call the fill mutation with namespace
    this.$store.commit("guest/fill", {
      email: "some@email"
    });

    // Call reset after 2 seconds 
    setTimeout(() => {
      this.$store.commit("guest/reset");
    }, 2000);
  }

商店

const initialState = {
  name: "dummyName",
  email: "dummy@initial" // put a value here so we can see if mapState works
};

const store = new Vuex.Store({
  modules: {
    guest: {
      namespaced: true,
      state: Object.assign({}, initialState),
      mutations: {
        fill(state, data) {
          Object.assign(state, data);
        },
        reset(state) {
          Object.assign(state, initialState);
        }
      }
    }
  }
});

关于vue.js - vuex 模块 appState 不适用于作为第一个参数传递的模块命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56926526/

相关文章:

javascript - App.vue 中的 BeforeRouteEnter 函数

unit-testing - _vuex.default.store 不是构造函数

javascript - 使用 VueX Store 中的计算属性进行 Ajax 调用的正确方法是什么

javascript - Vuex store模块状态下如何访问 'this'

wordpress - 在/wp-admin 中的 WordPress 插件中设置 Vue.js (vue-cli) 热重载

javascript - Vue.js 将函数传递给 Prop 不起作用

javascript - Vue.js 的计算状态和变异状态问题

javascript - 使用 v-model 改变 prop 的属性是不好的做法吗?

javascript - Vuex 在通过开发工具手动提交之前不会提交更改

javascript - Vuex Getter 未定义