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

Ways to determine if a browser is currently loading a fresh webpage

I'm experiencing an issue with my web app where the 'safety' code triggers a page reload if the server (Socket.IO) connection becomes silent for more than 5 seconds, often due to customer site firewall or broken-proxy issues. Although the S ...

The jquery live click event is not functioning properly on iPad devices

I am experiencing an issue with a webpage that has the following code to bind click events <script type="text/javascript"> $(".groupLbl").live("click", function(e) { var $target = $(e.currentTarget); ..... $.getJSON("/somelink.js ...

Move the cursor over the text to reveal an image

Hello, I'm trying to replicate the same animation effect as seen on these websites: and . Specifically, when hovering over the "selected works" section, an image is displayed. I suspect it's using a JavaScript library, but I can't seem to i ...

Is the reordering of items in an Angular JS array causing a malfunction with the first item

It appears that there may be a syntax error present in my code. Within my controller, I have a set of 4 functions: adding a new item, deleting the current item, moving an item backward (up) in the array, and moving an item forward (down) in the array. Al ...

Is there a way to utilize JavaScript in order to trigger a CSS animation to occur at a designated time during a video

I have a cool animated image element that I want to play at a specific point in time during a video using JavaScript. I'm not sure how to make it happen, but I know the .currentTime property could be the key. My goal is for the animation to only play ...

Tips for resolving the issue: Uncaught (in promise) SyntaxError: Unexpected end of input in Fetch API

When I click the button, I am executing this function. Despite adding a header in my API, an error is still being displayed. Here is the code snippet for the function: let getData = () => { console.log("getData function started"); ...

The `$scope variable fails to update in another controller`

I am currently facing an issue with updating a value on my view. Let me walk you through my code along with a brief explanation of the situation. The code may look messy as I have been experimenting with different combinations lately. The controller in qu ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

What's the process for including delivery charges in Stripe transactions?

I am facing an issue with Stripe where I am unable to incorporate delivery fees into my transactions. How can I successfully integrate this feature? let line_items = []; for (let productId of uniqIds) { const quantity = productsIds.filter(id => id == ...

Utilizing the power of d3.js within Angular 4

Currently, I have successfully implemented code to draw a polygon using the mouse in a normal JavaScript file. Now, I am looking to replicate the same functionality in my TypeScript file. Below is an excerpt from my d3.js file: //D3.JS VERSION 3 //------ ...

The Vue.js DevTools panel is mysteriously absent from the developer tools interface

I've been struggling to get the vue development tools panel to show up. Despite trying multiple solutions such as deleting and reinstalling the extension, hard refreshing, reopening the tools, adding Vue.config.devtools = true;, and various combinati ...

Click on a specific image in a table using Cypress with a specific source URL

I need help with a query for Cypress regarding a table of items, each item having active (blue) and not active (black) images. How can I set up this query? Below is an image of the table list: https://i.stack.imgur.com/74qzb.png And here is the HTML code ...

Ways to conceal submenu when clicking away from the navigation bar

I am looking to create a directive that will generate a navigation bar. Check out my code on JSFiddle here. Here is the code snippet from index.html : <html lang="fr" ng-app="activity" id="ng-app"> <div ng-controller="mainCtrl"> ...

Is an XMLHttpRequest necessary for updating a JSON file value using JavaScript?

Currently, I am working on a game feature that allows users to change their display name and then save it in a JSON file for easy access across different files and pages. I initially included an XMLHttpRequest in my code, but after stumbling upon this insi ...

What is the best way to prevent the page from constantly refreshing?

Recently, I developed a code snippet that detects the user's geolocation and changes the currency accordingly. The functionality works as intended, but there is an issue where the page keeps refreshing due to the presence of certain code. If I remove ...

Determine the frequency of each word and store the results in a PHP array

I need assistance creating a function called countWords($str) that can analyze any string of characters and determine how many times each word appears. For example: "hello world" letter || number of occurrences h 1 e ...

Serve static assets files based on the route path instead of using absolute paths

Within Express, I have set up the following route: app.get('/story/:username', function(req, res){ res.render('dashboard.ejs'); }); Prior to that, I am serving any static files located in /public: app.use(express.static(__dirname ...

Start the Express server by utilizing Grunt

Can anyone assist me with adding a task to my Gruntfile that will start my Express server instead of the default one? I attempted to create a task and use require("server.js"), but it doesn't seem to be working properly. When I run "grunt mytask", the ...

The SSE emitter sends out multiple signals, but occasionally the browser fails to receive them

When setting up an event emitter in a node.js/express application, I noticed that the events emitted are sometimes received multiple times by the front-end listener. Although I can confirm that emit is only called once, the same event gets emitted up to 4 ...

Using the dot operator to load an image

Is it possible to using the dot operator to load an image? Let's talk about this as a sample image URL <img src={{GET_PROFILE_DATA.googleProfileData.fullName}} alt="profile" class="home-screen-profile-image"> Take note of the unusual looking ...