Getting Started
At the center of every Vuex application is the store . A "store" is basically a container that holds your application state . There are two things that make a Vuex store different from a plain global object:
-
Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes.
-
You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations . This ensures every state change leaves a track-able record, and enables tooling that helps us better understand our applications.
The Simplest Store
NOTE
We will be using ES2015 syntax for code examples for the rest of the docs. If you haven't picked it up, you should !
After installing Vuex, let's create a store. It is pretty straightforward - just provide an initial state object, and some mutations:
import { createApp } from 'vue'
import { createStore } from 'vuex'
// Create a new store instance.
const store = createStore({
state () {
return {
count: 0
mutations: {
increment (state) {
state.count++
const app = createApp({ /* your root component */ })
// Install the store instance as a plugin
app.use(store)
Now, you can access the state object as
store.state
, and trigger a state change with the
store.commit
method:
store.commit('increment')
console.log(store.state.count) // -> 1
In a Vue component, you can access the store as
this.$store
. Now we can commit a mutation using a component method:
methods: {
increment() {
this.$store.commit('increment')
console.log(this.$store.state.count)