Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define getters on vuex module?

I am trying to improve vuex module but getting error below:

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

/stores/comments.js (module)

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
})

and here is my store.js that contains root state of the 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
})

Can you please help me to solve this issue. Tried but not understand what is the issue?

like image 770
bl4cksta Avatar asked Oct 29 '17 11:10

bl4cksta


People also ask

How do you access getters in mutations Vuex?

To access getters within Vuex mutations with Vue. js, we just use the state in the getter and call the getter with the state . //... const store = new Vuex.

Is Vuex getter cached?

Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. As of Vue 3.0, the getter's result is not cached as the computed property does.


1 Answers

  • You are creating store instance in store.js which is good
  • You are creating another store instance inside comment.js which is not good

As a start, Try to Change the export block on comment.js to this:

export default {
    state,
    getters,
    mutations,
    actions
}
like image 149
LiranC Avatar answered Oct 17 '22 00:10

LiranC