Building a Simple App Using Vuex
In this tutorial, we will be learning how to build a simple application using Vuex. Vuex is a state management pattern and 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.
Before we get started, make sure you have the following prerequisites:
- Basic understanding of Vue.js
- Node.js installed on your computer
- Vue CLI installed on your computer
We will be building a simple counter application that increments, decrements, and resets a value.
Setting Up The Project
Let's start by creating a new project using the Vue CLI. Open your terminal and run the following command:
vue create vuex-counter
Choose the default preset (babel, eslint) for the project setup. Once the project is created, navigate into the project folder.
cd vuex-counter
Installing Vuex
Next, we need to install Vuex. Run the following command to install Vuex:
npm install vuex
Setting Up Vuex Store
Now that we have Vuex installed, let's set up the Vuex store. Create a new file store.js
in the src
directory, and add the following code:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
},
decrement (state) {
if (state.count > 0) {
state.count--
}
},
reset (state) {
state.count = 0
}
},
actions: {},
modules: {}
})
Our store is pretty straightforward. We have a state
object that contains a count
property. We also have mutations
that will mutate the state.
Using The Store
We can now use this store in our App.vue
component. Replace the existing code in App.vue
with the following:
<template>
<div id="app">
<p>Count: {{ $store.state.count }}</p>
<button @click="$store.commit('increment')">Increment</button>
<button @click="$store.commit('decrement')">Decrement</button>
<button @click="$store.commit('reset')">Reset</button>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
#app {
text-align: center;
margin-top: 60px;
}
button {
margin: 10px;
}
</style>
The {{ $store.state.count }}
accesses the count state from the store. The @click="$store.commit('increment')"
calls the increment mutation when the button is clicked.
Wrapping Up
And that's it! You've just built a simple application using Vuex. Run npm run serve
in your terminal to start the development server and open your browser to http://localhost:8080
to see your app in action.
Remember, Vuex is not always necessary for small applications, where prop and event handling could suffice. However, in larger applications, managing state can be troublesome and Vuex is definitely helpful in such cases. Keep practicing and experimenting with Vuex. Happy coding!