Using Vue to turn a string into a mathematical operation

I'm in the process of creating a basic calculator using Vue, but I'm stuck on how to convert a string into a mathematical operation. I've already written the code for building the strings.

<template>
  <div>
    <input type="number" placeholder="number" v-model="number">
    <button @click = "addToOperation('+')">+</button>
    <button @click = "addToOperation('-')">-</button>
    <button @click = "addToOperation('*')">*</button>
    <button @click = "addToOperation('/')">/</button>
  </div>
</template>

<script>

export default {
    data() {
      return {
        number: '',
        operation: ''
      }
    },
    methods: {
        addToOperation(sign) {
          this.operation += this.number + sign 
        }
    }
}

</script>

Appreciate your help on this :).

Answer №1


I have discovered three methods to achieve this task:

The initial approach, which is not recommended:

var result;
eval("result = calculation");

Avoid using this method as it involves the use of eval, which poses security risks by evaluating Strings as code. It is best suited for personal websites with restricted access.

The alternative solution:

Create a function that breaks down the String by operators and executes the required mathematical operations. This method works well for simple calculators.

The final option:

Omitting the operator - Integrate mathematical actions within a query format. When calculations are needed, simply refer back to the query while maintaining the correct order of operations.

These are the three approaches that came to mind, and I trust they will be beneficial.
ShadowLp174

Answer №2

My suggestion would be to create separate functions for each operation. This approach results in more organized and easier-to-understand code, while also reducing the amount of unnecessary code:

<button @click = "add()">+</button>
<button @click = "subtract()">-</button>
<button @click = "multiply()">*</button>
<button @click = "divide()">/</button>

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

Upon reloading the page, the Vue getter may sometimes retrieve an undefined value

My blog contains various posts. Clicking on a preview will direct you to the post page. Within the post page, I utilize a getter function to display the correct post (using the find method to return object.name which matches the object in the array). cons ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface. However, I encount ...

When invoking Javascript, its behavior may vary depending on whether it is being called from a custom

Currently, I am in the process of implementing versioning capabilities to a custom entity called MFAs. However, I have encountered a peculiar issue. The problem arises from having a JavaScript web resource that is being invoked from two different locations ...

Transformed the Next.js Pages Router into an Application Router

Looking to make a change in my API written with Nextjs's Pages Router. Currently, it serves as a proxy for downloads and I am interested in converting it to the App Router method. Does anyone have any guidance on how to go about implementing this? imp ...

Sending objects as parameters to a class in JavaScript - an easy guide

Having trouble passing a parameter to the class for handling AJAX errors. The initial function is as follows: function GetLastChangePass(UserId) { var field = { id: UserId, } var fieldStringified = JSON.stringify(field) $.ajax({ ...

Cease the use of setInterval() once the component is no longer visible

I have a Nuxt component that receives logs from an API at regular intervals and displays them. How can I effectively pause the setInterval method when the component is not visible, and resume it when it becomes visible again? <template> <v-con ...

Are there any discussions underway about updating JSON standards to officially permit unquoted property names?

Technically speaking, the following JSON is considered invalid: { color: "blue", size: 14 } This is because according to the specification, property names like "color" and "size" should be enclosed in quotes, like this: { "color": "blue", "size" ...

Highcharts displaying black color after AJAX refresh

Struggling to implement real-time data visualization using Highcharts, I found myself tired of sifting through documentation and feeling confused. My solution involves using AJAX refresh. When the page initially reloads, my chart renders properly. However, ...

Is it possible to resend an AJAX request using a hyperlink?

Is it possible to refresh only the AJAX request and update the content fetched from an external site in the code provided below? $(document).ready(function () { var mySearch = $('input#id_search').quicksearch('#content table', ...

How to Embed a Javascript (jquery) Variable within a JSON Object

I have searched everywhere for a "simple answer" to this problem, but unfortunately, I cannot find a solution that aligns with my understanding of JSON and jQuery. Perhaps I am too much of a beginner in JSON to accurately formulate the right question (and ...

The error encountered is: "TypeError: req.flash does not exist as a function in NodeJs

When it comes to working with Registration on a Site, the Validation process is key. In this case, mongoose models are being used for validation and an attempt is being made to utilize Flash to showcase error messages within the Form. However, there seems ...

Is it possible to directly update the label text in AngularJS from the view itself?

I found the following code snippet in my HTML <span ng-class="newProvider ? 'newProvider' : ''" class="help-block"> {{ 'new-product.provider.helper' | locate }} </span> Whenever newProvider is se ...

Selenium Python Slider Button Element Visibility Issue

Currently, I am developing a parser to automate the process of clicking buttons on a website. However, I am encountering difficulties in clicking two specific buttons. The buttons I am aiming to click are "Elija el imports a financiar" and "Elija la mensu ...

Manipulating the information pulled from an external PHP script that is currently being displayed

Although I don't consider myself a professional, I am determined to learn some web languages this summer to be able to turn my design ideas into prototypes. Currently, I am struggling to figure out how to manipulate elements that are being echoed bac ...

AngularJS provides users with the ability to access additional information by matching specific identification

Is there a simple way in Angular to display the label of an item from an array without looping through it? I have an array of color options: $scope.colors=[ {id:"0",label:"blue"}, {id:"1",label:"red"}, {id:"2",label:"green"} ] And my data object store ...

A Step-by-Step Guide on Sending Response to ajaxError Callback in Perl

When working with JavaScript, I have a method of capturing errors that looks like this: $(document).ajaxError(function(event, jqxhr, settings, thrownError) { handleError(MSG_SAVE_ERROR); }); Now, my question is how can I retrieve an error message fro ...

Tips for refreshing the page without losing the values of variables

In my simulation.jsp file, I have the following code that retrieves simulation data from a struts2 action: $(document).ready(function() { var data='<s:property escape="false" value="simInfos" />'; } Once I perform the simulation with this ...

How can I show an item repeatedly with each button click in ReactJS?

Currently, I have a setup where I can display a checkbox and its label upon clicking a button. However, the limitation is that only one checkbox can be displayed at a time. Is there a way to modify this so that I can show multiple checkboxes simultaneous ...