In this tutorial, our focus will be on understanding how to manage state in Nuxt.js using Vuex. Vuex is a state management pattern + library 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. By the end of this tutorial, you will be able to:
Before getting started, you should have a basic understanding of:
- Vue.js and how components work
- ES6 JavaScript, especially arrow functions, modules, and Promises
- Node.js & npm/yarn
Vuex Store: In Nuxt.js, each application has a single store. We create the store by creating an index.js
file in the store
directory of our project. This file should export a method that returns a Vuex store instance.
State: The state in Vuex is the single source of truth for our data. It's where we define the data that needs to be shared across components.
Mutations: Mutations are functions that effect changes to the state. They are the only way to change state in Vuex.
Actions: Actions are functions that cause side effects and can involve asynchronous operations. Actions can commit mutations.
Getters: Getters are like computed properties for stores. They receive the state as their first argument.
Let's create a simple Vuex store that keeps track of a count.
store/index.js
export const state = () => ({
count: 0
})
export const mutations = {
increment(state) {
// mutate state
state.count++
}
}
In the above code, our state has a count property, and we have a single mutation that increments this count.
components/Counter.vue
<template>
<button @click="increment">{{ count }}</button>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
increment() {
this.$store.commit('increment')
}
}
}
</script>
In the above code, we are creating a button that displays the current count and increments the count when clicked.
Solutions can be found in the Vuex and Nuxt.js documentation. As you work through these exercises, consider how you might handle more complex state objects and actions that involve asynchronous operations.