Matthew Dangerfield (github.com/superMDguy)
May 30, 2019
A state management pattern + library for Vue.js applications
const store = new Vuex.Store({
state: {
name: 'John Doe',
favoriteColor: 'turquoise'
},
mutations: {
SET_NAME(state, newName) {
state.name = newName
},
SET_FAVORITE_COLOR(state, newFavoriteColor) {
state.favoriteColor = newFavoriteColor
}
}
})
store.commit('SET_NAME', 'Jane Doe')
console.log(store.state.name) // Jane Doe
const store = new Vuex.Store({
state: {
name: 'John Doe',
favoriteColor: 'turquoise'
},
mutations: {
SET_NAME(state, newName) {
state.name = newName
},
SET_FAVORITE_COLOR(state, newFavoriteColor) {
state.favoriteColor = newFavoriteColor
}
},
actions: {
async fetchUserDetails({ commit }, userId) {
const { name, favoriteColor } = await api.fetchUserDetails(userId)
commit('SET_NAME', name)
commit('SET_FAVORITE_COLOR', favoriteColor)
}
}
})
store.dispatch('fetchUserDetails', 'superMDguy').then(() => {
console.log(store.state.name) // retrieved name from API
console.log(store.state.favoriteColor) // retrieved favorite color from API
})
const store = new Vuex.Store({
state: {
name: 'John Doe',
favoriteColor: 'turquoise'
},
mutations: {
SET_NAME(state, newName) {
state.name = newName
},
SET_FAVORITE_COLOR(state, newFavoriteColor) {
state.favoriteColor = newFavoriteColor
}
},
actions: {
async fetchUserDetails({ commit }, userId) {
const { name, favoriteColor } = await api.fetchUserDetails(userId)
commit('SET_NAME', name)
commit('SET_FAVORITE_COLOR', favoriteColor)
}
},
getters: {
userSummary(state) {
return `${state.name}, favorite color is ${state.favoriteColor}`
}
}
})
console.log(store.getters.userSummary) // John Doe, favorite color is turquoise
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
},
state: { ... },
mutations: { ... },
actions: { ... }
})
console.log(store.state.a) // -> `moduleA`'s state
console.log(store.state.b) // -> `moduleB`'s state
Repo: https://git.io/fNHEF