如何在 vuex 模块上定义 getter?
How to define getters on vuex module?
我正在尝试改进 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
})
你能帮我解决这个问题吗?试过但不明白是什么问题?
尝试这种更模块化的方式 ;) :
将您的 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,
// ...
});
- 您正在
store.js
中创建 store
实例,good
- 您正在
comment.js
中创建 另一个 store
实例,不好
首先,尝试将 comment.js
上的导出块更改为:
export default {
state,
getters,
mutations,
actions
}
我正在尝试改进 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
})
你能帮我解决这个问题吗?试过但不明白是什么问题?
尝试这种更模块化的方式 ;) :
将您的 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,
// ...
});
- 您正在
store.js
中创建store
实例,good - 您正在
comment.js
中创建 另一个store
实例,不好
首先,尝试将 comment.js
上的导出块更改为:
export default {
state,
getters,
mutations,
actions
}