1

The user can input two values, and depending on what operator he selects the two values will either add to each other, subtract, divide or multiply with each other.

For example: user enters 45 and 32. If he selects the + operator, the result will be 77. If he then switch to * operator the result will be 1440.

Is this possible to do in a simple way, or I have to use v-if or something like that, and go through each one of them separately?

<select v-model="operator">
   <option value="+">+</option>
   <option value="-">-</option>
   <option value="*">*</option>
   <option value="/">/</option>
</select>
  • what is wrong with multiple if statements that you are trying to avoid? How is the user 'select'ing the + operator? – JimN Sep 04 '20 at 06:54

2 Answers2

1

You can do something like below. Make sure of the edge cases i.e when operator is / the input2 should not be 0.

methods: {
   doOperation(input1, input2) 
   {
      switch(this.operator)
      {
         case '+':
            return input1 + input2;

         case '-':
            return input1 - input2;

         case '*':
            return input1 * input2;

         case '/':
            return input1 / input2;
      }
   }
}
Sowmyadhar Gourishetty
  • 1,843
  • 1
  • 8
  • 15
1

Looking around I don't think this is possible out-of-the-box, however working from this answer, you should be able to set up an object as such in your Vue component's data object:

var operators = {
    '+': function(a, b) { return a + b },
    '-': function(a, b) { return a - b },
    '*': function(a, b) { return a * b },
    '/': function(a, b) { return a / b },
};

And then based on what is selected as the operator, and say the user also enters num1 and num2, which you also store in your Vue data component, you can set up a computed property result:

result() {
    return this.operators[this.operator](this.num1, this.num2);
}
Maylor
  • 548
  • 6
  • 6