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

An innovative countdown clock for WooCommerce that dynamically displays delivery time as a customizable shortcode

After successfully creating a Wordpress shortcode with a JavaScript counter, I encountered an issue: Back End - Counter functions properly: https://i.stack.imgur.com/qyHIL.png Front End - Counter not working (no console errors...): https://i.stack.imgu ...

The CSS media query isn't functioning properly on Safari browser

Currently, I am working on a project using React JS and CSS. In order to make it responsive, I have implemented media queries. However, I have encountered an issue where the media query is not functioning properly in Safari browsers on both phones and PC ...

Creating complex concave shapes using Three.js from a point cloud

Currently facing a challenge in dynamically creating shapes in three.js from a point cloud. While ConvexGeometry works well for convex shapes, it becomes complex when dealing with concave shapes. The process involves drawing a line on the 2D plane (red li ...

Comparison of various nodejs scripts

Snippet One net.createServer(function(socket){ socket.on('data',function(id){ getUserDetails(function(){console.log(id)}); }); }); function getUserDetails(next){ next(); } Snippet Two net.createServer(function(socket){ ...

Placing an absolutely positioned element on top of other elements

Currently, I am working on a frontendmentor website and encountering difficulty in positioning the shopping cart div above all the other elements. Initially, I attempted to use z-index for this purpose, but it seems that it does not work with elements havi ...

Using two distinct buttons to submit information using various methods

When button 1 is clicked, I want it to update the row. When button 2 is clicked, I want it to create another row. This is the controller code for updating: public function update(Request $request, $id){ $pay = Payroll::find($id); $pay ->idnumb ...

Steps for assigning an id to a newly created div within a parent div while in design mode

Imagine creating a div element with the attribute contenteditable="true", and then checking the console for what happens next: 1st. In the console, you only see a simple div tag. <div id="typbody" contenteditable="true" style="width:100%; height:200px ...

Utilizing the power of Ionic Native with AngularJS 1 for Cordova SQLite Integration

I am interested in implementing DeepLinking in my hybrid application using ionic-native. Currently, I have a functioning project with an SQLite database that has been tested on both iOS and Android platforms. However, when I include ionic.native in my app ...

Designating a certain function to a designated button

On my page, I have three different forms with submit buttons in each. There is a code that is supposed to change the value of a button in a specific form when clicked. However, whenever I click on any submit button, all the values in the buttons of the v ...

Material Design Forms in Angular: A Winning Combination

I'm currently working on developing a form using Angular Material. This form allows the user to update their personal information through input fields. I am utilizing "mat-form-field" components for this purpose. However, there are certain fields tha ...

Error Message: SCRIPT5 - Permission Denied When Trying to Open PDF with Javascript

Despite searching through multiple posts on SO, I have yet to find a solution to my issue. We operate a web form within our LAN that utilizes Javascript's OPEN function to open PDF files. Up until recently, everything was working smoothly. However, ...

Having issues with importing images in Next.js using the Next Images package

Having trouble with importing images locally from the images folder. Error message: "Module not found: Can't resolve '../images/banner1.jpg'" https://i.stack.imgur.com/Dv90J.png Attempting to access images in ImagesSlider.js file at compo ...

Arranging extensive menu sections and content containment

I am currently working on enhancing my website's navigation by creating a mega menu. However, I am facing issues with the organization of the divs containing the ul content. In the fiddle linked below, you can see that "Africa", "Asia", and "Oceania" ...

Unable to retrieve information from the JSON object

Here's the script I'm working with: <script type="text/javascript> function getData(username){ $.ajax({ url: '{% url "data" %}', data: { ' ...

Developing a specialized command-line application for currency conversion is my current project

Currently, I am working on developing a command-line application for currency exchange. I have created an interface to define the structure of an object array that will store the keys and values of currency names along with their current values in the inte ...

Attempting to nest an AJAX request within the success callback of another AJAX request

I am attempting to execute two jQuery ajax calls, with the second call being made from the success callback of the first. I have experimented with different variations of the code, such as adjusting the brackets. Below is my attempted code snippet: $.aja ...

Exploring the Depths of React Routing: The Power

I'm currently diving into React and trying to figure out how to create dynamic routes similar to partial pages in Angular. Here is my main App component: import React from 'react'; import Header from '../common/Header'; export d ...

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...

Receiving JSON information from a web address using Javascript

I'm currently faced with a challenge in extracting JSON data from a web server. Despite the absence of errors in my code, I encounter difficulties displaying any output. Below is a snippet of the issue: <!DOCTYPE HTML> <html> <head ...

Struggling to concentrate using jQuery?

When the search icon is clicked, I want the focus to be on the input so the user can start typing right away without having to manually click on it. Although I tried using focus(), it doesn't seem to work for this particular input. $('.header__ic ...