Vue可组合返回字符串

dpiehjr4  于 2022-12-14  发布在  Vue.js
关注(0)|答案(1)|浏览(204)

我有下面的vue可组合方法:

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

当我把下面的参数传递给函数useCalculator(10,11,"add")时,我得到了下面的结果:“一零一一”
虽然我已经定义了传入参数的数据类型,但该方法通过将它们作为字符串包含来返回值

ivqmmu1c

ivqmmu1c1#

首先,如果以后要修改result的值,请不要将其声明为const,而应将其声明为var
第二,不需要在函数props中指定de变量的类型,只需将输入转换为数字即可。例如:

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

相关问题