【问题标题】:How do correctly add a getter to a Vuex Module?如何正确地将 getter 添加到 Vuex 模块?
【发布时间】:2019-01-17 19:57:54
【问题描述】:

每当我注册模块时,我都会尝试创建一个 Vuex 模块,我得到一个未定义的状态,即使没有任何东西调用我刚刚创建的 getter。我能够正确调用操作而没有错误。

这是我的模块。 customer.js

export default {
    namespaced: true,

    state: {
        login: false,
    },

    getters: {
        isLoggedIn: (state) => {
            console.log(state);
            state.login;
        }
    },

    mutations: {
        set_login: (state, login) => {
            state.login = login;
        },

        set_orders: (state, orders) => {
            state.orders = orders;
        },

    },

    actions: {
        newsletter_subscribe: (context, email) => {
            //- TODO 
        },
    }
}

我已经通过 registerModule 函数注册了。

import Customer from './customer';
store.registerModule('customer', Customer, {
    preserveState: true
});

每当我打开开发人员工具时,它都会提醒我这一点。 未捕获的 ReferenceError:未定义状态 在 isLoggedIn (customer.js:11) 在 WrappedGetter (vuex.esm.js:734)

我的吸气剂有什么问题吗?

我只注意到在打开 Vue 开发工具的情况下调用了 getter,因为我尝试在 getter 中放置一个警报,看看在没有传入状态的情况下还会触发什么。

【问题讨论】:

  • 尽量不要将其导出为default。不知道namespaced: true(vuex.vuejs.org/guide/modules.html#namespacing)会不会喜欢。
  • 你会推荐什么其他方式?我正在使用名称间距,所以我可以轻松地做Store.dispatch('customer/newsletter_subscribe',true); 它适用于动作,而不是突变和吸气剂。我还使用命名空间,因为需要将更多模块应用于商店。

标签: vuejs2 vuex


【解决方案1】:

我设法通过给我的商店一个空白状态来解决它!

const store = new Vuex.Store({
    state: {}
});

并正常注册模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2021-09-15
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多