Fiddle : here
Currently, I am in the process of developing a web application using Vue 2 with Vuex. Within my store, I aim to retrieve state data from a getter. My intention is for the getter to trigger a dispatch and fetch the data if it discovers that the data has not yet been populated.
This is how my Vuex store looks like:
const state = {
pets: []
};
const mutations = {
SET_PETS (state, response) {
state.pets = response;
}
};
const actions = {
FETCH_PETS: (state) => {
setTimeout(function() {
state.commit('SET_PETS', ['t7m12qbvb/apple_9', '6pat9znxz/1448127928_kiwi'])
}, 1000)
}
}
const getters = {
pets(state){
if(!state.pets.length){
state.dispatch("FETCH_PETS")
}
return state.pets
}
}
const store = new Vuex.Store({
state,
mutations,
actions,
getters
});
However, an error message keeps popping up:
Uncaught TypeError: state.dispatch is not a function(…)
I am aware that this can be resolved by implementing it within the beforeMount
hook of a Vue component. But considering that I have multiple components utilizing the same Vuex store, I need to decide on a single component for this implementation and understand its implications on the other components.