We all know that Vuex is a very powerful state management system when used with VueJS. And when you are using it with NuxtJS, it’s even more fun to use. But sometimes it is a little confusing. Mainly in the initial stage of setting up the Store. What I did to save some time on the configuration process is I created a set of code snippets. I am going to share them here with instructions so others can get benefit from them.
Nuxt Store Example (index.js)
export const state = () => ({
job_ids: []
})
export const mutations = {
STORE_JOB_IDS(state, job_ids) {
state.job_ids = job_ids
}
}
export const actions = {
storeJobIds({commit}, job_ids) {
commit('STORE_JOB_IDS', job_ids)
}
}
export const getters = {
getJobIds(state) {
return state.job_ids
}
}
Nuxt Store Example (cars.js)
export const state = () => ({
cars: []
})
export const mutations = {
STORE_CARS(state, cars) {
state.cars = cars
}
}
export const actions = {
storeCars({commit}, cars) {
commit('STORE_CARS', cars)
}
}
export const getters = {
getCars(state) {
return state.cars
}
}
Using Actions in Pages
1. Inside asyncData()
store.dispatch('storeJobIds', response) // for index.js
store.dispatch('cars/storeCars', response) // for store named cars.js
Make sure to add {store} as a parameter to the async method like below:
async asyncData({ $axios, store })
2. Inside Vue methods
this.$store.dispatch('storeJobIds', response) // for index.js
this.$store.dispatch('cars/storeCars', response) // for store named cars.js
Using Getters in Pages
{{ $store.getters['getJobIds'] }} // for index.js
{{ $store.getters['cars/getCars'] }} // for store named cars.js