Vue.js 表格输入框限制:限制输入值不超过初始数量
您可以通过使用v-model指令来实现该功能。首先,在表格的每一行中,您可以使用v-model指令将输入框与对应的数据绑定起来。然后,您可以使用@input事件监听输入框的值变化,并在事件处理函数中进行验证,确保输入的值不大于带出的数量。
以下是一个示例代码:
<template>
<table>
<thead>
<tr>
<th>商品名称</th>
<th>带出数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.quantity }}</td>
<td>
<input type="number" v-model="item.inputQuantity" @input="handleQuantityChange(item)" />
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '商品1', quantity: 10, inputQuantity: 10 },
{ id: 2, name: '商品2', quantity: 5, inputQuantity: 5 },
// 其他数据...
]
};
},
methods: {
handleQuantityChange(item) {
if (item.inputQuantity > item.quantity) {
item.inputQuantity = item.quantity; // 如果输入的值大于带出的数量,将其设置为带出的数量
}
}
}
};
</script>
在上述代码中,每一行的输入框使用v-model指令绑定了item.inputQuantity,这样输入框的值会自动与inputQuantity属性保持同步。当输入框的值发生变化时,会触发@input事件,调用handleQuantityChange方法进行验证。如果输入的值大于带出的数量,那么将其设置为带出的数量,以确保输入的值不会大于带出的数量。
请根据您的实际需求进行修改和调整。
原文地址: https://www.cveoy.top/t/topic/qnES 著作权归作者所有。请勿转载和采集!