如何在vuex模块上定义getter?

时间:2017-10-29 11:21:05

标签: javascript vue.js vuex

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

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

/stores/comments.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
})

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

2 个答案:

答案 0 :(得分:4)

  • 您正在store中创建store.js实例良好
  • 您正在store内创建另一个 comment.js实例不好

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

export default {
    state,
    getters,
    mutations,
    actions
}

答案 1 :(得分:0)

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

将你的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,
    // ...
});