[Vuejs]-Vue composable returns string

1๐Ÿ‘

I did not see any issue in your code, As you are passing the params as a number it should concatenate properly and result should be 21. Also, As you define the param types in the function definition. It will throw an error during compile time itself if you will pass the num1 and num2 as a string instead of number.

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');
<script src="https://unpkg.com/vue@3.0.0-beta.14/dist/vue.global.js"></script>

<div id="app">
</div>

-1๐Ÿ‘

First, do not declare result as a const if you are going to modify its value later, instead declare it as var.

And second, instead of require the type of de variables in the function props. Just convert your inputs to numbers. Example:

var result = ref(0);
      const useCalculator = (num1, num2, operation) => {
      //Here you convert the inputs in floats numbers
        num1 = parseFloat(num1);
        num2 = parseFloat(num2);
        //Here you can also use parseInt() if you just want to have integer numbers

        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;
      };

Leave a comment