Vuex is the state management library for Vue.js.
Vuex makes use of a single object to manage its state. This object contains all our application-level states and serves as a single source of truth.
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, description: 'Buy Educative Course', done: true },
{ id: 2, description: 'Take a nap', done: false }
]
}
})
It is simply an object that takes in values. We can use these values to store data that is to be accessed by our app.
To access our states in our components, we can use various approaches. Here we see how we can get access to our store using this.$store
.
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
We would need to provide the store option to the root instance when initializing the Vue project. Calling this.$store
would give all child components access to the store.
const app = new Vue({
el: '#app',
store,
components: { Dashboard }
})
mapState
helper to access states in componentsWe can also make use of the mapState
helper which allows us to get rid of the many $this.store
in the computed property.
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
count: state => state.count,
loading: state => state.loading,
isLoggedIn: state => state.isLoggedIn
})
}
}