我正在使用 VueJS 添加选择字段并且它工作正常,但我想添加验证。
如果用户在第一个选择中选择 8mm
,那么 8mm
将在其他选择标签中禁用。
<div class="form-group" v-for="(input,k) in inputs" :key="k">
<select v-model="input.thickness" name="thickness-`${k}`" class="basicRate block w-full p-3 mt-2 text-gray-700 bg-gray-200 appearance-none focus:outline-none focus:bg-gray-300 focus:shadow-inner" required>
<option disabled selected value> -- Select thickness -- </option>
<option value="8">8mm</option>
<option value="10">10mm</option>
<option value="12">12mm</option>
<option value="16">16mm</option>
<option value="20">20mm</option>
<option value="25">25mm</option>
</select>
<input type="text" class="form-control" v-model="input.qty">
<span>
<i class="fas fa-minus-circle" @click="remove(k)" v-show="k || ( !k && inputs.length > 1)"></i>
<i class="fas fa-plus-circle" @click="add(k)" v-show="k == inputs.length-1"></i>
</span>
</div>
var app = new Vue({
el: "#app",
data: {
inputs: [
{
thickness:'',
qty: ''
}
]
},
methods: {
add(index) {
this.inputs.push({ thickness: '', qty: '' });
},
remove(index) {
this.inputs.splice(index, 1);
}
}
});
如您所见,前两个下拉列表具有相同的值,这意味着用户可以选择相同的值。我正在寻找简单的验证,如果用户选择某个选项,那么他或她不会在其他下拉列表中选择相同的值。
提前致谢。
答案 0 :(得分:1)
您可以使用每个选择的值的数组。只需在触发 change
事件时更新数组,并根据这些值有条件地添加 disabled
属性:
var app = new Vue({
el: "#app",
data: {
thicknesses: [],
inputs: [{
thickness: '',
qty: ''
},
{
thickness: '',
qty: ''
},
{
thickness: '',
qty: ''
},
{
thickness: '',
qty: ''
},
]
},
methods: {
handleChange(e) {
this.thicknesses = [...this.$refs.selects.children].map(select => {
return select.children[0].value;
})
},
add(index) {
this.inputs.push({
thickness: '',
qty: ''
});
},
remove(index) {
this.inputs.splice(index, 1);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" ref="selects">
<div class="form-group" v-for="(input,k) in inputs" :key="k">
<select v-model="input.thickness" name="thickness-`${k}`" required @input="handleChange($event)">
<option disabled selected value> -- Select thickness -- </option>
<option value="8" :disabled="thicknesses.includes('8')">8mm</option>
<option value="10" :disabled="thicknesses.includes('10')">10mm</option>
<option value="12" :disabled="thicknesses.includes('12')">12mm</option>
<option value="16" :disabled="thicknesses.includes('16')">16mm</option>
<option value="20" :disabled="thicknesses.includes('20')">20mm</option>
<option value="25" :disabled="thicknesses.includes('25')">25mm</option>
</select>
</div>
</div>