【问题标题】:How to define getters on vuex module?如何在 vuex 模块上定义 getter?
【发布时间】:2017-10-29 11:21:05
【问题描述】:

我正在尝试改进 vuex 模块,但出现以下错误:

Uncaught Error: [vuex] getters should be function but "getters.getComments" in module "comments" is [].

/stores/cmets.js(模块)

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

Vue.use(Vuex);

const state = {
    comments: []
}

const getters = {
    getComments: state => state.comments
}
const mutations = {
    setComments(state, comments) {
        state.comments = comments
    }
}

const actions = {
    setComments(context, data) {
        context.commit('setComments', data)
    }
}
export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions
})

这是我的 store.js,其中包含 vuex 的根状态 store.js

import Vue from 'vue';
import Vuex from 'vuex';
import commentsModule from './stores/comments'
Vue.use(Vuex);
const state = {
}

const getters = {
}

const mutations = {
}

const actions = {

}

export default new Vuex.Store({
    state,
    getters,
    mutations,
    modules: {
        comments: commentsModule
    },
    actions
})

你能帮我解决这个问题吗?试过但不明白是什么问题?

【问题讨论】:

  • 不应在模块文件中创建新的Store,然后将新存储导出到假定存储本身。商店本身的代码丢失了。
  • @LiranC 实际上,它并没有丢失。我没有分享 store.js 因为它只包含里面的模块
  • 我认为你应该包含它,有些奇怪。
  • @LiranC 我已经在帖子中添加了它

标签: javascript vue.js vuex


【解决方案1】:
  • 您正在store.js 中创建store 实例,这
  • 您正在创建 另一个 storecomment.js 内的实例,这不好

首先,尝试将comment.js 上的导出块更改为:

export default {
    state,
    getters,
    mutations,
    actions
}

【讨论】:

  • 是的,这是有道理的,但这次我收到无法读取未定义的属性 'getComments' 错误
  • 也许你有错字?在标题中您将文件称为“comment.js”,并在代码中导入 cmets.js
  • 其实是对的。我刚刚不小心输入了帖子
  • 哪一行触发了新的错误?你在做什么会产生undefined 错误?
  • 我想我现在真的很困惑。像这样访问模块的 getter 是否错误:this.$store.getComments
【解决方案2】:

尝试这种更模块化的方式;):

将您的 getter 移至外部模块。

例如在app/js/store/getters.js:

export const getComments = state => {
    return state.comments;
};

例如在app/js/store/index.js 内部:

import Vue from 'vue';
import Vuex from 'vuex';
import * as getters from './getters';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        comments: [],
    },
    getters,
    // ...
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 2021-09-15
    • 2018-02-10
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2017-10-01
    相关资源
    最近更新 更多