首页 > 解决方案 > 如何将最小值和最大值添加到我的 Vue 计数值

问题描述

用户可以单击+-按钮来增加和减少值。如何添加最小值和最大值,例如 min = 1 和 max = 10 <span>[[ count ]]</span>

我的Vue.js应用程序:

<div id="app">
    <a class="btn" v-on:click="increment">Add 1</a>
    <a class="btn" v-on:click="decrement">Remove 1</a>

    <span>[[ count ]]</span>
  </div>

  <script>

    const App = new Vue({
      el: '#app',
      delimiters: ['[[',']]'],
      data() {
        return {
          min: 1,
          max: 10,
          count: 1
        }
      },
      methods: {
        increment() {
          this.count = this.count === this.max ? this.max : this.count + 1;
        },
        decrement() {
          this.count = this.count === this.min ? this.min : this.count + 1;
        }
      }
    })

  </script>

更新: 上面的代码现在正在运行。

1)我如何将我的<span>[[ count ]]</span>变成一个<input type="number" min="0" max="10" />,由这个按钮控制?

2)我如何添加一个类,例如disabled当 [[ count ]] === 1 时?

更新 2:

我将其更改为输入字段:

  <input type="number" name="lineItems[{{ product.id }}][quantity]" value="{{ quantity }}" v-model.number="quantity" min="{{ product.minPurchase }}" max="{{ product.calculatedMaxPurchase }}" class="custom-qty__qty-field">

并通过 min 和 plus 按钮调整输入值:

<script>
    const app = new Vue({
      el: '#app',
      delimiters: ['[[',']]'],
      data() {
        return {
          quantity: 1,
          max: {{ product.calculatedMaxPurchase }},
          min: {{ product.minPurchase }}
        }
      },
      methods: {
        increment() {
          //this.count++
          this.quantity = this.quantity === this.max ? this.max : this.quantity + 1;
        },
        decrement() {
          //this.count--
          this.quantity = this.quantity === this.min ? this.min : this.quantity - 1;
        }
      }
    })
  </script>

例如,包含 ShopWare 后端设置的变量{{ product.minPurchase }}twig

这是一种干净的方式吗?当计数达到 1 时如何添加 CSS 类,以便禁用按钮?

标签: vuejs2

解决方案


检查count期间是否已经达到极限incrementdecrement并采取相应措施。

increment() {
  this.count = this.count === 10 ? 10 : this.count + 1;
}
decrement() {
  this.count = this.count === 1 ? 1 : this.count - 1;
}

如果需要,您还可以制作minmax数据属性而不是硬1编码10

编辑后:

如果您改用数字输入,则无需方法即可解决此问题。所需要做的就是将您的数据绑定到输入,如下所示:

<input type="number" v-model="count" :min="min" :max="max" />

请看下面的演示:

new Vue({
  el: "#app",
  data() {
    return {
      min: 1,
      max: 10,
      count: 1
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="number" v-model="count" :min="min" :max="max" />
  
  <span class="instructions">&lt;&lt; Mouseover the input to change</span>
  <div class="count">Count: {{ count }}</div>
</div>


推荐阅读