I attempted to create a calculator using vue.js. Unfortunately, I encountered an issue where the second string value does not get appended on the calculator screen upon clicking the next button. This problem arose after implementing some logic for arithmetic operations in the method section. My apologies for any language errors.
Below is the code from 'calculator.vue' in components
<template>
<div class="calculator">
<div class="display">{{current || '0'}}</div>
<div class="btn" @click="clear">AC</div>
<div class="btn" @click="sign">+/-</div>
<div class="btn" @click="percent">%</div>
<div class="btn operator" @click="divide">/</div>
<div class="btn" @click="append('7')">7</div>
<div class="btn" @click="append('8')">8</div>
<div class="btn" @click="append('9')">9</div>
<div class="btn operator" @click="times">x</div>
<div class="btn" @click="append('4')">4</div>
<div class="btn" @click="append('5')">5</div>
<div class="btn" @click="append('6')">6</div>
<div class="btn operator" @click="minus">-</div>
<div class="btn" @click="append('1')">1</div>
<div class="btn" @click="append('2')">2</div>
<div class="btn" @click="append('3')">3</div>
<div class="btn operator" @click="plus">+</div>
<div class="btn zero" @click="append('0')">0</div>
<div class="btn" @click="dot">.</div>
<div class="btn operator" @click="equal">=</div>
</div>
</template>
<script>
export default {
data() {
return {
current: "",
previous: null,
operator: null,
operatorClicked: false,
};
},
methods: {
clear() {
this.current = "";
},
sign() {
this.current =
this.current.charAt(0) === "-"
? this.current.slice(1)
: `-${this.current}`;
},
percent() {
this.current = `${parseFloat(this.current) / 100}`;
},
append(number) {
this.current = `${this.current}${number}`;
},
dot() {
if (this.current.indexOf(".") === -1) {
this.append(".");
}
},
setPrevious() {
this.previous = this.current;
this.operatorClicked = false;
},
divide() {
this.operator = (a, b) => a / b;
this.setPrevious();
},
times() {
this.operator = (a, b) => a * b;
this.setPrevious();
},
minus() {
this.operator = (a, b) => a - b;
this.setPrevious();
},
add() {
this.operator = (a, b) => a + b;
this.setPrevious();
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.calculator {
font-size: 30px;
width: 300px;
margin: 0 auto;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: minmax(50px, auto);
}
.display {
grid-column: 1/5;
background-color: #333;
color: white;
}
.zero {
grid-column: 1/3;
}
.btn {
background-color: #f2f2f2;
border: 1px solid #999;
cursor: pointer;
}
.operator {
color: white;
background-color: orange;
}
</style>