rgoodwin
rgoodwin

Reputation: 45

How do I use an if statement in a Vue.js function?

What I am trying to do is have the result function offer two different equations:

return this.number1*(this.number2/100) if the {{ basketballbet.odds }} value is positive

return this.number1*(100/this.number2) if the {{ basketballbet.odds }} value is negative.

Does anyone know if this is possible?

code:

<div id="odds_calculator">
<p>Placing <input type="number" name="number1" v-on:input= "update_number1"> on this bet would win you $XXXX if you were to win the bet.</p>

  <p>Bet Amount: [[ number1  ]] </p>
  <p>Odds: {{ basketballbet.odds }}</p>

  <hr>
  <p>Result: [[ result() ]]</p>
</div>
<script>
new Vue({
  delimiters: ['[[',']]'],
  el: '#odds_calculator',
  data: {
    number1: 0,
    number2: {{ basketballbet.odds }},
  },
  methods: {
    update_number1: function (event) {
      this.number1 = event.target.value;
    },
    result: function () {

      return this.number1*(this.number2/100);
    },

  },
});
</script>

Upvotes: 0

Views: 275

Answers (3)

Jon P
Jon P

Reputation: 19797

Yes you can but this is also the perfect opportunity to introduce yourself to the ternary operator

new Vue({
  delimiters: ['[[',']]'],
  el: '#odds_calculator',
  data: {
    number1: 0,
    number2: {{ basketballbet.odds }},
  },
  methods: {
    update_number1: function (event) {
      this.number1 = event.target.value;
    },
    result: function () {
      //here is the aforementioned ternary operator
      return this.number2 < 0 ? this.number1*(100/this.number2) : this.number1*(this.number2/100);
    },

  },
});

Upvotes: 2

Jakub A Suplicki
Jakub A Suplicki

Reputation: 4801

Yes, it is. If it is simply about a positive or negative value then you can use Math.sign(). Check here for more info.

For example:

if (Math.sign(this.number2) == 1) {
  //positive
}else if (Math.sign(this.number2) == -1) {
  //negative
}else {
  //zero
}

Good luck!

Upvotes: 3

diegooblue
diegooblue

Reputation: 1

result: function() {
  if (this.number1 > 0) {
    return this.number1 * (this.number2 / 100);
  } else if (this.number1 < 0) {
    return this.number1 * (100 / this.number2);
  }
},

Upvotes: 0

Related Questions