简体   繁体   中英

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>

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM