-
What exactly is Vuex?
Vuex is a state management paradigm and framework for Vue.js applications. It serves as a centralized repository for all of the components of an application.
-
Why would you want to use Vuex?
Vuex is a state management system. To truly comprehend what Vuex works, you must first comprehend the concept of state in a SPA and how it interacts with other elements.
-
Installation – NPM
npm install vuex@next --save
-
The simplest example for Vuex
=> Initialize the store
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)
=> Trigger a state change
store.commit('increment') console.log(store.state.count)
=> Access store in Vue component
methods: { increment() { this.$store.commit('increment') console.log(this.$store.state.count) } }