首页 文章

复选框上的VueJS切换功能

提问于
浏览
0

我想知道使用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

    这是您通常使用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>
    

相关问题