Consider a simple Vue blog:
I'm using Vuex as my datastore and I need to set up two getters: a getPost
getter for retrieving a post
by ID, as well as a listFeaturedPosts
that returns the first few characters of each featured post. The datastore schema for the featured posts list references the posts by their IDs. These IDs need to be resolved to actual posts for the purposes of showing the excerpts.
store/state.js
export const state = {
featuredPosts: [2, 0],
posts: [
'Lorem et ipsum dolor sit amet',
'Lorem et ipsum dolor sit amet',
'Lorem et ipsum dolor sit amet',
'Lorem et ipsum dolor sit amet',
'Lorem et ipsum dolor sit amet',
]
}
store/getters.js
export default getPost = (state) => (postID) => {
return state.posts[postID]
}
export default listFeaturedPosts = (state, getters) => () => {
console.log(getters) // {}
return state.featuredPosts.map(postID => getters.getPost(postID).substring(0, EXCERPT_LENGTH);
}
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import * as getters from './getters'
import * as mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state,
getters,
mutations
})
According to the documentation, the getters
parameter can be used to access other getters. However, when I try to access getters
from inside listFeaturedPosts
, it's empty, and I get an error in the console due to getters.getPost
being undefined in that context.
How do I call getPost
as a Vuex getter from inside listFeaturedPosts
in the example above?