Looking for a solution to fix the VueJS calculator that only works once?

My calculator project using VueJS, HTML and CSS is almost complete. However, I'm facing an issue where it only works once. For example, if I input 6x3, it correctly gives me 18. But if I then clear the result and try to input a new calculation like 3 x 2, it does not work as expected and displays 32 instead. The problem persists until I reload the webpage, which creates a frustrating loop. I'm in need of assistance to resolve this issue.

Below is the HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <link rel="stylesheet" type="text/css" href="Calcss.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link rel="icon" href="Cal.png">
    <link href="https://fonts.googleapis.com/css2?family=Belanosima:wght@600&family=Pangolin&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div class="Title">
        <div class="bar"> 
            <h1>CalculationMaster</h1>
        </div>
    </div>
    <div class="all">
        <div id="app">
            <div id="calculator">
                <div id="screen">{{currentNum}}</div>
                    <div @click="oposite" class="btn">-/+</div>
                    <div @click="percentage" class="btn">%</div>
                    <div @click="log" class="btn">log</div>
                    <div @click="clear" class="btn operator">C</div>
                    <div @click="enter(7)" class="btn">7</div>
                    <div @click="enter(8)" class="btn">8</div>
                    <div @click="enter(9)" class="btn">9</div>
                    <div @click="divide" class="btn operator">÷</div>
                    <div @click="enter(4)" class="btn">4</div>
                    <div @click="enter(5)" class="btn">5</div>
                    <div @click="enter(6)" class="btn">6</div>
                    <div @click="multiply" class="btn operator">x</div>
                    <div @click="enter(1)" class="btn">1</div>
                    <div @click="enter(2)" class="btn">2</div>
                    <div @click="enter(3)" class="btn">3</div>
                    <div @click="subtract" class="btn operator">-</div>
                    <div @click="enter(0)" class="btn">0</div>
                    <div @click="decimal" class="btn">.</div>
                    <div @click="equal" class="btn operator">=</div>
                    <div @click="addition" class="btn operator">+</div>
            </div>
        </div>
            <div id="hello">
                <img :src="ci" alt="Cipheros Image" style="width: 50px; border-radius: 10px; box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);"/>
                <p style="font-size: 10px;">
                Created by Cipheros.
                </p>
            </div>
    </div> 
<script src="CalJs.js"></script>  
<script>
    new Vue ({
        el: "#hello",
        data: {
            ci: 'Cipheros.png'
        },  
    });
</script>  
</body>
</html>

Here is the CSS code: 
'''
body {
    background-color: #2c2929;
    color: white;
    text-align: center;
    justify-content: center;
    align-items: center;
    font-family: 'Belanosima', sans-serif;
    font-family: 'Pangolin', cursive; 
}
.bar {
    background-color: rgb(57, 165, 105);;
    padding: 1px 0;
    margin-top: 2.5%;
    margin-bottom: 3%;
}
h1{
    font-size: 40px;
}
.all {
    display: flex;
    text-align: center;
    justify-content: center;
    align-items: center;
    margin-left: 40px;
    gap: 15px;
}
#calculator {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-auto-rows: minmax(40px, auto);
    width: 80vh;
    text-align: center;
    font-size: 30px;
    margin: 10px auto;
    background-color: #595757;
    border-radius: 10px;
}
#screen{
    display: grid;
    grid-column: 1/5;
    margin-bottom: 5%;
    align-items: center;
    text-align: center;
    justify-content: center;
    
}
.btn {
    border-bottom: 1px solid #ccc;
    border-left: 1px solid #ccc;
    border-radius: 5px;
    cursor: pointer;
    margin: 1.5px;
    background-color: #807d7d;
}
.operator {
background-color: mediumseagreen;
}
#hello{
    gap: 1px;
}
'''

And here is the JS code using VueJS:
'''
new Vue ({
    el: '#calculator',
    data:{
        currentNum: '',
        operation: '',
        clicked: false
    },
    methods:{
        enter(number){
            if (this.clicked){
            this.currentNum = '';
            this.clicked = false
            } 
            this.currentNum = `${this.currentNum}${number}`;
        },
        clear(){
            this.currentNum = '';
        },
        oposite() {
            this.currentNum = this.currentNum.charAt(0) === '-' ?
                this.currentNum.slice(1) : `-${this.currentNum}`;
        },
        decimal(){
            if (this.currentNum.indexOf('.') === -1){
                this.enter('.');
            }
        },
        percentage(){
            this.currentNum = `${parseFloat(this.currentNum) / 100 }`
        },

        log(){
            this.operation = `log(${this.currentNum})`;
            this.currentNum = `${Math.log(parseFloat(this.currentNum))}`;
        },

        previous(){
            this.previous = this.currentNum
            this.clicked = true;
        },

        multiply(){
            this.operator = (a, b) => a * b;
            this.previous();
        },

        addition(){
            this.operator = (a, b) => a + b;
            this.previous();
        },

        subtract(){
            this.operator = (a, b) => a - b;
            this.previous();
        },

        divide(){
            this.operator = (a, b) => a / b;
            this.previous();
        },
        equal(){

            if (this.operation) {
                this.currentNum = `${this.operation} = ${this.currentNum}`;
                this.operation = '';
            }
            else
            this.currentNum = `${this.operator(
                parseFloat(this.previous),
                parseFloat(this.currentNum),
            )}`
            this.previous = null;

        },
    }
});
'''


I would greatly appreciate any help in resolving this issue so that the calculator functions properly all the time.
[enter image description here](https://i.sstatic.net/PAq2F.png)

Answer №1

The issue:

precedente() has been mistakenly changed from a method to a variable with a value of null in two different sections, causing errors when trying to call it as a method.

  1. Within the precedente() function where
    this.precedente = this.numCurrent;
  2. Inside the equal() function where this.precedente = null;

Solution:

Replace instances of this.precedente (without the parentheses) with a different variable name.

For instance, update it to previousNum:

precedente() {
    this.previousNum = this.numCurrent; // updated
    this.clicked = true;
},

equal() {
    if (this.operation) {
        this.numCurrent = `${this.operation} = ${this.numCurrent}`;
        this.operation = '';
    } else {
        this.numCurrent = `${this.operator(
            parseFloat(this.previousNum), 
            parseFloat(this.numCurrent)
        )}`;
    }
    this.previousNum = null; // updated
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What purpose does Webpack serve in injecting React?

Within my webpack entry file, I have the following code snippet: import ReactDOM from 'react-dom'; import Layout from './components/Layout'; // ... dialog = document.createElement("dialog"); ReactDOM.render(<Layout dialog={dialog} ...

Toggle the visibility of table rows using checkboxes

I'm working with checkboxes to toggle the visibility of specific rows in a table based on their content matching the selected checkbox values. Checkboxes: <input type='checkbox' name='foo1' value='foo1' v-model="sele ...

CSS Layout - Float: What's floating to the top?

Are there any CSS techniques available to make floated blocks fill in both upwards and in their float direction? For example - https://i.sstatic.net/uo06B.png Instead of - https://i.sstatic.net/oEijA.png I know this can be achieved using JavaScript li ...

Utilize jQuery.ajaxComplete to identify the location of the AJAX request

I have an event: $(document).ajaxComplete that is functioning perfectly. Yet, I am looking to determine whether ajax took place at a particular spot within the document. Is there a method to identify which ajax call was made? $(document).ajaxComplete(fu ...

Struggling with eliminating spacing between v-text-field elements and labels in Vuetify

Struggling to reduce the vast gap between rows in my Vuetify project. I've attempted using CSS and Vuetify spacing options, but haven't had any luck. Desired layout: Current layout: <v-container> <v-row> <v-col cols=" ...

Having difficulty with delaying the loading of a div layer and javascript after the page has initially loaded

I've been struggling to make this script wait a few seconds after the page has loaded, but I haven't been successful so far. Despite trying some solutions from similar questions here, nothing seems to be working. Any help you can provide would b ...

Conceal the Div containing the specified class

I was hoping to hide the first DIV if the second DIV is displayed on the front end, and vice versa upon page load. If the first DIV is set to 'block,' then the second DIV should be set to 'none.' And If the second DIV is set to &apos ...

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...

How can Javascript split main.js into two separate files using import or require?

Currently, my main.js file is functioning perfectly despite its length. However, I am interested in organizing my code by separating the functions related to 'y' into a separate file. In PHP, this process can be easily achieved with require(&apos ...

JMeter recording displays a script alert error notification

After recording the JMeter script on blazemeter, it initially worked fine on the website. However, upon running the jmx file, I encountered an error message: "alert("Something went wrong. Please try again");window.history.back();" I&a ...

What is the best way to create a miniaturized image of a webpage for sharing on Facebook?

I'm looking for a way to post a link to users' Facebook walls with a thumbnail image of their created page. The page is in HTML format and stored as a series of 'elements' in the database, each with its size, position, and content. Is i ...

Unable to connect to a style sheet

I'm in the process of developing a web application and I'm facing an issue with linking a stylesheet to my app. Check out my code below: <html> <head> <title>Bubble</title> </head> <link rel=" ...

How to use RegExp to locate the final return statement within a JavaScript code string

Take a look at this code snippet: cont x = 10; function foo() { return x; // ;; end of function ;; // /* here is a some text here too */ } function bar() { return 10 } return foo() + bar(); // ;;done;; // /* yolo yolo */ This string cont ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

Showing the incorrect ziggy package

After successfully setting up the tightenco/ziggy package as per the documentation, I encountered an issue with the template displaying the entire list of addresses. Please help me identify where I may have made a mistake. <head> @routes ...

Angular button will be disabled if the form control is empty

Is there a way to deactivate the search button when the text box is empty? I attempted to use the "disabled" attribute on the search button, but it didn't work. Here is my HTML code: <div class="col-md-5 pl-0"> <div class="in ...

What is the best way to extract data from the ajax.done() function?

My question revolves around the function shown below: $.ajax({ url: "../../getposts.php" }).done(function(posts) { var postsjson = $.parseJSON(posts); }); I am wondering how I can access the variable postsjson outside of the .done() function sco ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

A guide to integrating Material-UI with your Meteor/React application

I encountered an issue while trying to implement the LeftNav Menu from the Material-UI example. The error message I received is as follows: While building for web.browser: imports/ui/App.jsx:14:2: /imports/ui/App.jsx: Missing class properties transf ...