Need help fixing my issue with the try-catch functionality in my calculator program

Can someone assist me with my Vue.js calculator issue? I am facing a problem where the output gets added to the expression after using try and catch. How can I ensure that both ERR and the output are displayed in the {{output}} section? Any help would be appreciated!

Here is the specific part causing trouble:

                else if (but == "=") {
                    try {
                        eval(this.expression)
                        // this.output = eval(this.expression)
                    } catch (error) {
                            this.output = "ERR"
                            // throw e;
                        }
                }

For reference, here is the full code:

<html>

<head>
    <title>calculator</title>

    <!-- Vue 3: development -->
    <script src="https://unpkg.com/vue@next"></script>

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
        integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ"
        crossorigin="anonymous">
    <link rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
        crossorigin="anonymous">
    <meta charset="UTF-8">
</head>

<body>
    <div id="app" class="container" style="width: 400px;">

        <div class="row border m-3 text-right" style='height:100px;'>
            <div class="col">
                {{expression}}
                {{output}}
            </div>
        </div>
        <div class="row text-center">
            <div class="col">
                <template v-for="i in button.length">
                    <button id="button[i-1]"class="btn btn-light m-2" style="width:50px" @click="action(button[i-1])">
                        {{button[i-1]}}
                    </button>
                    <br v-if=" i % 4 == 0">
                </template>
            </div>
        </div>

            

        </div>


    </div>

</body>

<script>
    Vue.createApp({
        data() {
            return {
                expression: "",
                output: "",
                button: ["1","2","3","AC", "4", "5", "6", "+", "7", "8", "9", "-", "0", ".", "="]
            };
        },
        methods: {
            action(but) {
                console.log(but)
                if (this.expression == "" && (but ==  "+" || but =="-")){
                    this.expression = "0" + but
                }
                else if (but == "=") {
                    try {
                        eval(this.expression)
                        // this.output = eval(this.expression)
                    } catch (error) {
                            this.output = "ERR"
                            // throw e;
                        }
                }
                else{
                    this.expression = this.expression + but
                }
                // if =
                if (but == "AC") {
                    this.expression = ""
                    this.output = ""
                }
            }
        },
        computed: {
        }
    }).mount('#app')

</script>
</body>

</html>

Answer №1

After careful observation, I realized my mistake - it was simply missing a <br>. :( Oh my goodness, I wasted so much time debugging

                {{expression}}
                <br>
                {{output}}

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

Jquery code that mimics pressing a key downwards is not functioning properly to execute a keyboard shortcut

I would like to express my gratitude in advance for any time and effort dedicated to this matter. So, here's the situation: I have a script that is meant to simulate a key press event after 3 seconds once the page is loaded. The goal was to trigger a ...

Protection of Angular expressions

I have been following the PhoneCat tutorial for AngularJS and found it very helpful up until step 6 where links are generated dynamically from angular expressions: http://localhost:8000/app/{{phone.imageUrl}} Although the tutorial mentions that ngSrc pre ...

Incorporate the HTML CTA on top of the background image within the email template

In my email template, I am trying to place an HTML CTA over a background image. The code works perfectly on all email clients including mobile and desktop, except for Outlook where the alignment of the CTA copy is off. Below is the code snippet along with ...

Using JavaScript to transform base64 encoded strings into images

I'm currently working on an app using Titanium and I have a base64 string that I need to convert into an image from JSON data. Any assistance you can provide would be much appreciated. Thank you! ...

Use the knockout textInput plugin in combination with the maskedinput plugin

Is there a simple way to use data-bind="textInput: aProperty" and apply an input mask or automatic formatting while the user is typing? Although using the masked input plugin somewhat works, it results in losing the real-time updates that Knockout's ...

Facing issues with receiving API response through Postman encountering error { }

In my MongoDB database, I have created documents for Families, Users, and Devices (https://i.stack.imgur.com/oeDU0.png). My goal is to retrieve all devices associated with a specific family using the family's Id provided in the HTTP request. For examp ...

Error is being returned by the JSONP callback

Looking to grasp JSONP. Based on my online research, I've gathered that it involves invoking a function with a callback. Other than that, is the way data is handled and the data format similar to JSON? I'm experimenting with JSONP as shown below ...

Configuration file stored within the node_modules directory

I have developed a generic npm package that contains my business logic. However, I require access to some information stored in my google cloud storage configuration files. How can I retrieve this data when my package is located within the node_modules fol ...

The auto-play feature fails to function on iPhone devices when using Reactjs

I am currently working with Reactjs and Nextjs. I have a video on my website that is functioning properly on Android phones but not on iPhones. How can I resolve this issue? I have attempted the following code: <video loop autoplay='' muted> ...

What is the reason behind an Express function requiring both the Request and Response as parameters?

Exploring the world of node.js and familiarizing myself with Express. The code snippet below has left me puzzled: var server = http.createServer(handleRequest); function handleRequest(req, res) { var path = req.url; switch (path) { case "/n": ...

Receive a positive or negative data message through Ajax Response

Exploring Ajax for the first time, I am eager to incorporate database interaction using AJAX in JQUERY by connecting to a PHP script. $(function() { $.ajax({ type: "POST", url: "response.php", ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

Performing a PHP Curl request and an ajax query to an ASP.NET page

I am attempting to send an ajax query to an ASP.NET page. Here is the algorithm I am following: 1. There is a form on my webpage; 2. When the user fills in all the fields, they click the submit button; 3. Upon clicking the submit button, JavaScript sends ...

Is it necessary for an embedded YouTube video to automatically play with sound?

My current project involves developing a Web Application where the client has specified that videos must autoplay with sound when a user visits it. Here is a snippet of what I have implemented: HTML: <embed id="video1" src="" wmode="transparent" type= ...

Changing the context results in the entire component being re-rendered

Currently, I am encountering a challenge where I have two different components within my Layout.js component that need to "share" props with each other. To address this issue, I introduced a ContextProvider named IntegrationProvider. However, a new proble ...

Issue with ng-repeat rendering on screen

Creating a breadcrumb has been my latest project, so I decided to develop a service specifically for this purpose. In order to display all the breadcrumbs, I utilized an ng-repeat in my HTML. Additionally, I set up an event listener for '$routeChange ...

Configuring Proxy Settings for WebpackDevServer

I need assistance setting up a proxy using WebpackDevServer in my React/Node chrome extension. Currently, my server is running on localhost:4000, and the React frontend is on localhost:5000. When trying to access the route /api/user/ticket using Axios, I ...

The count of records in MongoDB by the current month

Recently delving into MongoDB, I found myself in need of a way to retrieve the count of posts made in the current month. Keeping timestamps true in my PlateModel model, it appears as follows: { timestamps: true } The current code snippet in my Controller ...

Initiating the Gmail React component for composing messages

Is it possible to use a React application to open mail.google.com and prefill the compose UI with data? This is a requirement that I need help with. ...

The bug in Polymer 1.0 where a custom element is causing issues when clicking under the toolbar

Issues have arisen with a custom element I created, named <little-game></little-game>. Here is the template code for <little-game></little-game>: <template> <a href="{{link}}"> <paper-material elevation=& ...