Vuex is a state management pattern + library (Flux-inspired Application Architecture) for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `
<div>8</div>
`,
// actions
methods: {
increment () {
this.count++
}
}
})
A Vuex “store” is basically a container that holds your application state.
Configure vuex in vuejs ecosystem.
import Vuex from "vuex";
Vue.use(Vuex)
Provide an initial state object and some mutations.
// Make sure to call Vue.use(Vuex) first if using a module system
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
Vuex mutations are similar to any events with a string
type
and ahandler
. The handler function is where we perform actual state modifications, and it will receive the state as the first argument.
Trigger state change with commit and access state variables.
store.commit('increment')
console.log(store.state.count) // -> 1