首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在vuex模块上定义getter?

如何在vuex模块上定义getter?
EN

Stack Overflow用户
提问于 2017-10-29 11:21:05
回答 2查看 2.9K关注 0票数 7

我正在努力改进vuex模块,但是在下面出现了错误:

代码语言:javascript
复制
Uncaught Error: [vuex] getters should be function but "getters.getComments" in module "comments" is [].

/stores/comments.js (模块)

代码语言:javascript
复制
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的根状态。

代码语言:javascript
复制
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
})

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-10-29 12:24:19

  • 您正在store.js中创建store.js实例,即good
  • 您正在创建,在comment.js中创建另一个 store实例,即不是很好的

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

代码语言:javascript
复制
export default {
    state,
    getters,
    mutations,
    actions
}
票数 8
EN

Stack Overflow用户

发布于 2017-10-29 11:40:53

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

将您的getter移动到外部模块。

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

代码语言:javascript
复制
export const getComments = state => {
    return state.comments;
};

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

代码语言:javascript
复制
import Vue from 'vue';
import Vuex from 'vuex';
import * as getters from './getters';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        comments: [],
    },
    getters,
    // ...
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46999565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档