Vue composable yields a string value

I am currently using a Vue composable method that looks like this:

import {
  ref
} from 'vue';

const useCalculator = (num1: number, num2: number, operation: string) => {
  const result = ref(0);

  switch (operation) {
    case 'add':
      result.value = num1 + num2;
      break;
    case 'sub':
      result.value = num1 - num2;
      break;
    case 'mul':
      result.value = num1 * num2;
      break;
    case 'divide':
      result.value = num1 / num2;
      break;
    default:
      result.value = 0;
  }

  return result;
}

After passing the params useCalculator(10,11,"add") to the function, I noticed that I received the unexpected result of "1011."

Despite specifying data types for the input parameters, it seems that the method is concatenating them as strings instead of performing the expected calculation.

Answer №1

Your code looks good and there doesn't seem to be any issue. Since you are passing the parameters as numbers, they should concatenate properly resulting in 21. Additionally, by defining the parameter types in the function definition, any attempt to pass num1 or num2 as strings instead of numbers will throw an error during compile time.

Below is a working demo:

const { ref, onMounted } = Vue;

let options = {
  setup: function () {
    const useCalculator = (num1, num2, operation) => {
      const result = ref(0);
      switch (operation) {
        case 'add':
          result.value = num1 + num2;
          break;
        case 'sub':
          result.value = num1 - num2;
          break;
        case 'mul':
          result.value = num1 * num2;
          break;
        case 'divide':
          result.value = num1 / num2;
          break;
        default:
          result.value = 0;
      }
      return result.value;
    }

    onMounted(function () {
      console.log(useCalculator(10, 11, 'add'))
    });
  }
};

let app = Vue.createApp(options).mount('#app');

Answer №2

One important tip is to avoid declaring result as a const if it needs to be modified later on; in such cases, it's better to declare it using var instead.

Another suggestion is to skip specifying the type of variables in the function props and simply convert your inputs to numbers. For example:

var result = ref(0);
      const useCalculator = (num1, num2, operation) => {
      //Convert the inputs into floating-point numbers here
        num1 = parseFloat(num1);
        num2 = parseFloat(num2);
        //If you only want integer numbers, you can also consider using parseInt()

        switch (operation) {
          case "add":
            result.value = num1 + num2;
            break;
          case "sub":
            result.value = num1 - num2;
            break;
          case "mul":
            result.value = num1 * num2;
            break;
          case "divide":
            result.value = num1 / num2;
            break;
          default:
            result.value = 0;
        }
        return result;
      };

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

Leveraging Discord.JS to seamlessly transport users in Discord to their designated voice channel by assigning roles

I'm attempting to transfer all users with a specific role from a voice channel using a command like: !summon @role This command should bring only the users with that specific role to the voice channel where the command was entered My current code is ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

Progress of file uploads on the client side using Vue JS

I'm facing a challenge in creating a loading bar that shows the progress when a file is selected for upload in a form. Most of the examples I come across online demonstrate the loading bar after hitting an 'upload' button, but in my case, I ...

ReactJS Components failing to load on initial site visit, only appearing after refreshing for the second time

var img; var dateFormat = require('dateformat'); var count; let arrayIMG = [] var storage = firebase.storage(); var storeRef = storage.ref('images/') const config = { ... }; if (!firebase.apps. ...

Is there a way to set an image as the background of my HTML screen?

{% extends "layout.html" %} {% block app_content %} <div> {% from "_formhelpers.html" import render_field %} <form method="post" enctype="multipart/form-data"> <div class = "container"> < ...

Error encountered while attempting to import external JSON data into SurveyJS

This Codepen example showcases SurveyJS using a simple JSON structure: var json = { "questions": [{ "type": "text", "title": "Test question 1", "name": "Test question" }, { "type": "comme ...

"Incorporate React Redux to dynamically load an endless stream of items in batches of x at a time

In order to efficiently display search results using React - Redux, I want to limit the number of displayed results while maintaining optimal performance. Here is my current approach for getting and displaying the results: handleSubmit(event) { event ...

Error occurred while trying to fetch the Backbone.js collection due to undefined value of 'this._byId'

I am currently working with coffeescript and my code is quite straightforward: class SomeCollection extends Backbone.Collection constructor: (@options) -> url: -> "#{$SCRIPT_ROOT}/some/data/#{@options.someId}" model: SomeModel class SomeV ...

Error: Value of incoming scope in Angular Directive is not defined

When working in html, I passed an object into a directive like this: <lcd-code ldcCode="{{ detail.program.ldcCode }}"></lcd-code> The value of detail.program.ldcCode is "PSIH"... However, in the Directive, it is showing up as undefined: var ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

Eclipse - enhancing outline view by utilizing require.js define(...)

My code is structured within the define(...) function in the following format: define(['angular'], function(angular) { function foo () { console.log("Hi") ; } function foo2 () { console.log("Hi") ...

Locate a piece of text with jQuery and enclose it within a specified container

Check out this code <form method="get" name="form_delivery"> Pick the country where you want your delivery<br> <select name="deliverymethod"> <option value="0" selected="selected">Choose a country / region</option> ...

Issue with comparing strings in Typescript

This particular issue is causing my Angular application to malfunction. To illustrate, the const I've defined serves as a means of testing certain values within a function. Although there are workarounds for this problem, I find it perplexing and woul ...

Performing a single AJAX call from a JavaScript loop is more efficient than iterating through multiple AJAX calls

I am working with a 2D array in JavaScript. Currently, I have a for loop where I make an AJAX call to update the database. I understand that this approach is not efficient, and I am seeking a way to update the database with just one AJAX call within the ...

developing a checkbox group with Vue.js

I am working with 2 arrays - one contains possible checkbox variants and the other contains already saved checked boxes. In my VUEJS template, I have created a simple example: <ul> <li v-for="cit in possable"> ...

Updating Angular 2 template based on specific conditions of model values

I want to update a view only when the total votes reach a number that is a multiple of ten. I am incrementing a random element in an array called rows every 10 milliseconds, ultimately adding up to the total number of votes. Is there a simple way in angula ...

Efficiently organizing items within a list on Ionic

Currently, I have an ion-list structured as follows: <ion-list *ngFor = "let chat of Chats"> <ion-item (click) = "openChat(chat.id)"> <ion-label> <h2> {{chat.username}} </h2> ...

Ways to retrieve a property that is dynamically generated within a React component

In the code snippet below, I have registered the TextField name as M1.${index}.M13-M14 and it is marked as required. However, I am unable to locate the property accessor using errors[`M1.${index}.M13-M14`]?.type, which prevents the error from being gener ...

Winning opportunities created by using credits in the slot machine

**Greetings, I have created a slot machine using JavaScript, but I am looking to enhance the player's chances based on their credits. Can anyone guide me on how to achieve this? Essentially, I want the player's odds to increase proportionally wit ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...