首页 > 解决方案 > 如何为动态输入设置最大值?

问题描述

我有动态输入的 vue 表单。

第一个。
用户在表格2中注册总股数。他开始通过添加他需要的动态输入来部分地向股东发行这个总额
第三他提交表格。
我的任务是避免过度发布。

我无法弄清楚如何避免向股东发行的股份超过其注册总额/

Ex:
totalSharesAmount = 100
shareholder[0] - shares_amount = 50 
shareholder[1] - shares_amount = 20 //70 total
shareholder[2] - shares_amount = 30 //100 total. can't be more than 100

我的数据:

data() {
return {
    totatSharesAmount: 100
    shareholders: [{share_amount: '', share_price: ''}]
    }
}

我的验证方法(计算),在这里我需要帮助:

sharesToFounders() {
    return {
      required: true,
      max_value: this.totalSharesAmount - this.shareholder['shares_amount'] //need help here
   }
}

标签: javascriptvue.jsvee-validate

解决方案


您需要计算来跟踪剩余点。当有剩余点时,您需要一个函数将元素添加到数组中。您需要连接一个观察者来调用该函数。下面的代码片段就是这样做的。

new Vue({
  el: '#app',
  data() {
    return {
      totalPoints: 100,
      foundersPoints: []
    };
  },
  methods: {
    addPoint() {
      this.foundersPoints.push({
        points_amount: null,
        point_price: null
      });
    }
  },
  watch: {
    remainingPoints: {
      handler(v) {
        if (v > 0 && this.pointValues.every((v) => v > 0)) {
          this.addPoint();
        }
        if (v <= 0 || isNaN(v)) {
          // Remove any zeros, probably just the last entry
          this.foundersPoints = this.foundersPoints.filter((o) => o.points_amount > 0);
        }
      },
      immediate: true
    }
  },
  computed: {
    pointValues() {
      return this.foundersPoints.map((o) => o.points_amount);
    },
    remainingPoints() {
      const used = this.pointValues.reduce((a, b) => a + b, 0);

      return this.totalPoints - used;
    }
  }
});
:invalid {
  border: solid red 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="p in foundersPoints">
    <input v-model.number="p.points_amount" type="number" min="1" :max="p.points_amount + remainingPoints">
  </div>
  <div>Remaining shares: {{remainingPoints}}</div>
</div>


推荐阅读