In this tutorial, we will build a simple calculator app using Vue.js and Vuex. Vue.js is a progressive JavaScript framework for building user interfaces, and Vuex is a state management pattern and library for Vue.js applications. By using Vuex, we can manage the state of our calculator app more efficiently.
Prerequisites
To follow this tutorial, you should have basic knowledge of HTML, CSS, and JavaScript. You should also have Node.js and npm (Node Package Manager) installed on your development machine. If you don’t have them installed, you can download them from the official Node.js website (https://nodejs.org).
Setting Up Project
Let’s start by creating a new Vue.js project using the Vue CLI.
Open your terminal or command prompt and run the following command:
vue create calculator-app
This command will create a new directory named “calculator-app” and scaffold a new Vue.js project inside it. You will be prompted to choose a preset configuration for your project. For this tutorial, you can choose the default preset by pressing the Enter key.
Once the project is created, navigate into the project directory by running the following command:
cd calculator-app
Now, let’s install the Vuex library by running the following command:
npm install vuex
Creating the Calculator Component
Next, let’s create a new file called “Calculator.vue” inside the “src/components” directory. This file will contain the main logic and markup for our calculator app.
Open the “Calculator.vue” file and add the following code:
<template>
<div class="calculator">
<input type="text" v-model="input" readonly>
<div class="buttons">
<button v-for="button in buttons" :key="button" @click="handleClick(button)">
{{ button }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
input: "",
buttons: ["7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"]
};
},
methods: {
handleClick(button) {
if (button === "=") {
this.calculate();
} else {
this.input += button;
}
},
calculate() {
try {
this.input = eval(this.input);
} catch (error) {
this.input = "Error";
}
}
}
};
</script>
In this code, we define a Vue.js component called “Calculator”. We use the v-model
directive to bind the “input” data property to the text input field. This allows us to update the input value based on user interactions.
We also define a “buttons” array that contains all the buttons we want to display on our calculator. We loop through this array using the v-for
directive to generate the buttons dynamically.
Inside the methods section, we define two methods: “handleClick” and “calculate”. The “handleClick” method is called whenever a button is clicked. If the button is the equal (=) sign, we call the “calculate” method. Otherwise, we concatenate the button value to the input value.
The “calculate” method uses the eval
function to evaluate the mathematical expression in the input field. If an error occurs during evaluation, we display the “Error” message.
Importing and Using the Calculator Component
Now that we have created the “Calculator” component, let’s import and use it in the main App component.
Open the “src/App.vue” file and replace its contents with the following code:
<template>
<div id="app">
<Calculator />
</div>
</template>
<script>
import Calculator from "./components/Calculator";
export default {
name: "App",
components: {
Calculator
}
};
</script>
<style>
#app {
margin: 0 auto;
max-width: 300px;
padding: 20px;
text-align: center;
}
</style>
In this code, we import the “Calculator” component and register it as a local component inside the “App” component. Then we use the “Calculator” component within the template of the “App” component.
We also add some basic styling to center the app on the page and limit its width to 300 pixels.
Setting Up Vuex
Now let’s set up Vuex to manage the state of our calculator app.
Create a new directory called “store” inside the “src” directory. Inside the “store” directory, create a new file called “index.js” and add the following code:
import Vuex from "vuex";
export default new Vuex.Store({
state: {
input: ""
},
mutations: {
setInput(state, input) {
state.input = input;
}
},
actions: {
updateInput({ commit }, input) {
commit("setInput", input);
}
},
getters: {
getInput(state) {
return state.input;
}
}
});
In this code, we import Vuex and create a new Vuex store. Inside the store, we define the initial state with an empty “input” property.
We also define a “setInput” mutation that is responsible for updating the “input” property in the state. The “updateInput” action is used to commit the “setInput” mutation and pass the new input value as an argument.
Finally, we define a “getInput” getter to retrieve the current input value from the state.
Connecting Vuex to the Calculator Component
Now let’s connect the Vuex store to the “Calculator” component.
Open the “Calculator.vue” file and update its code as follows:
<template>
<div class="calculator">
<input type="text" :value="input" readonly>
<div class="buttons">
<button v-for="button in buttons" :key="button" @click="handleClick(button)">
{{ button }}
</button>
</div>
</div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
computed: {
...mapGetters(["getInput"]),
input: {
get() {
return this.getInput;
},
set(value) {
this.updateInput(value);
}
}
},
methods: {
...mapActions(["updateInput"]),
handleClick(button) {
if (button === "=") {
this.calculate();
} else {
this.input += button;
}
},
calculate() {
try {
this.input = eval(this.input);
} catch (error) {
this.input = "Error";
}
}
}
};
</script>
<style>
.button {
margin: 0.5rem;
padding: 0.5rem 1rem;
}
</style>
In this code, we import the mapGetters
and mapActions
functions from Vuex to map the store’s getters and actions to the component’s computed properties and methods, respectively.
We use the mapGetters
function to add a getInput
computed property to the component. This property retrieves the input value from the store.
We also modify the input
computed property to use the Vuex store. It gets the value from the getInput
computed property and sets the value using the updateInput
action.
Finally, we use the mapActions
function to add the updateInput
action to the component’s methods.
Registering the Store in the App
Now that we have set up the store and connected it to the “Calculator” component, let’s register the store in the main App component.
Open the “src/main.js” file and update its code as follows:
import Vue from "vue";
import App from "./App.vue";
import store from "./store";
Vue.config.productionTip = false;
new Vue({
store,
render: h => h(App)
}).$mount("#app");
In this code, we import the store from the “store” directory and pass it as a property to the Vue instance. This registers the store globally for all components in the app.
Running the App
Finally, let’s run the app and see the calculator in action!
Open your terminal or command prompt and run the following command:
npm run serve
This command will compile the app and start a local development server. Once the compilation is complete, the server will provide you with a local URL (e.g., http://localhost:8080/) where you can access the app.
Open your web browser and navigate to the URL provided by the development server. You should see the calculator app rendered on the page.
Try using the calculator app by clicking on the buttons. The input field should update accordingly, and the result will be displayed when you click the equal (=) sign.
Congratulations! You have successfully built a calculator app with Vue.js and Vuex. You can now extend and customize the app based on your requirements.
Conclusion
In this tutorial, we learned how to build a simple calculator app using Vue.js and Vuex. We started by setting up a new Vue.js project using the Vue CLI and installed the Vuex library. Then we created a “Calculator” component to handle the logic and markup of the app.
We imported and used the “Calculator” component in the main App component, and added basic styling to the app. We also set up a Vuex store to manage the state of the app and connected it to the “Calculator” component.
Finally, we registered the store in the main App component and ran the app to see the calculator in action.
Vue.js and Vuex provide a powerful combination for building complex and scalable applications. With Vuex, you can easily manage state and achieve a more predictable flow of data in your app.