复选框上的VueJS切换功能

时间:2018-08-08 23:53:24

标签: vue.js vuejs2

我想知道使用VueJS中的复选框切换功能的正确方法是什么。

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

我想做的是选中折扣后,我想在视图中更新一个字符串,以显示从正常价格到折扣价格的折扣价格。例如$ 10至$ 8

我可以简单地将其添加到@click="toggleDiscount"上方的复选框中吗

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

}

然后在toggleDiscount内,我只是检查discount是对还是假,然后做我所拥有的事情。还是@ click =“”不适合在复选框中使用?

1 个答案:

答案 0 :(得分:0)

通常在这里使用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>

相关问题