我有带有动态输入的Vue形式。
1号用户以表格形式注册股份总数
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: ''}]
}
}
我的validate方法(已计算),在这里我需要帮助:
sharesToFounders() {
return {
required: true,
max_value: this.totalSharesAmount - this.shareholder['shares_amount'] //need help here
}
}
答案 0 :(得分:1)
您需要计算才能跟踪剩余点。当剩余点时,需要一个函数将元素添加到数组中。您需要连接watcher才能调用该函数。下面的代码片段可以做到这一点。
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>
答案 1 :(得分:1)
一种解决方法:跟踪当前总数,并在输入时使用验证器方法允许用户更改或阻止更改。
标记:
<div id="app">
<div class="row"><span>Total:</span><input type="number" v-model="totalPoints"></div>
<div v-for="(item, index) in foundersPoints" class="row">
<input type="number" v-on:input="updateValue(index)" v-model="foundersPoints[index].points_amount"><span v-if="foundersPoints[index].alert" class="alert">{{foundersPoints[index].alert}} <button v-on:click="dismissAlert(index)">OK</button></span>
</div>
</div>
Validator方法:
updateValue(idx) {
let value;
if (this.tempSum > this.totalPoints) {
const overage = this.totalPoints - this.tempSum;
value = Number(this.foundersPoints[idx].points_amount) + overage;
} else {
value = Number(this.foundersPoints[idx].points_amount);
}
this.foundersPoints[idx].points_amount = value;
},
用于跟踪的当前总计(计算属性):
computed: {
tempSum() {
const pointsAmounts = this.foundersPoints.map(item => Number(item.points_amount));
return pointsAmounts.reduce((acc, t) => acc + Number(t), 0);
}
},
在这个小提琴中实际操作:https://jsfiddle.net/ebbishop/vu508Lgc/
这不适用于用户减少允许的总积分的情况。 (用户的总数为60,然后将三个点的值分别设置为20。如果用户将总数更改为40,那么加起来为60的输入将如何处理?)