代码之家  ›  专栏  ›  技术社区  ›  Kiow

“打开VueJS切换函数”复选框

  •  0
  • Kiow  · 技术社区  · 6 年前

    我想知道在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 回复  |  直到 6 年前
        1
  •  1
  •   Bert    6 年前

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