VueJS toggle function on checkbox

I wonder what the proper way is to toggle a function using a checkbox in VueJS.

<input v-model="discount" type="checkbox" name="discount">

What I want to do is when the discount is checked I want to update a string in my view displaying the discounted price from normal price to discounted price. Eg $10 to $8

can I simply add this to the checkbox above @click="toggleDiscount"

toggleDiscount() {
if (this.discount == true) {
        //show discount
      } else {
        //hide discount
      }

}

Then inside the toggleDiscount I simply check if discount is true or false and do the things I have. Or is @click="" not the right thing to use here on a checkbox?

1 answer

  • answered 2018-08-09 00:40 Bert

    This is where you would typically use a computed property.

    console.clear()
    
    new Vue({
     el: "#app",
     data: {
       discount: false,
       price: 10,
       discountedPrice: .8
     },
     computed:{
       computedPrice() { 
         return this.discount ? this.price * this.discountedPrice : this.price
       }
     }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <label><input type="checkbox" v-model="discount"> Apply Discount</label> 
      <hr>
      Price: {{computedPrice}}
    </div>