如何将 v-model="item.checked"
作为下面 validations()
中 if
的条件?
<table>
<tr v-for="(item, i) of $v.timesheet.items.$each.$iter" >
<div>
<td>
<input
type="checkbox"
v-model="item.checked"
v-on:click="disable(i)"
/>
</td>
<td>
<input
type="text"
:id="'total_hour-' + i"
/>
</td>
</div>
</tr>
<tr>
<div>
<td>
<button
type="button"
class="btn btn-sm btn-primary"
@click="itemCount++"
>Add Row
</button>
</td>
</div>
</tr>
</table>
<script>
import { required, minLength } from "vuelidate/lib/validators";
export default {
data() {
return {
itemCount: 1,
timesheet: { items: [{ total_hour: "", checked: false }] },
}
},
methods: {
disable(index){
const check =
document.getElementById('total_hour-' + index).disabled
$('#total_hour-' + index).attr('disabled', !check);
}
},
watch: {
itemCount(value, oldValue) {
if (value > oldValue) {
for (let i = 0; i < value - oldValue; i++) {
this.timesheet.items.push({
total_hour: "",
checked: false,
})
}
} else {
this.timesheet.items.splice(value);
}
}
},
validations() {
if ( ? ) {
return {
timesheet: {
items: {
required,
minLength: minLength(1),
$each: { total_hour: {required} }
}
}
}
} else {
return {
timesheet: {
items: {
required,
minLength: minLength(1),
$each: { total_hour: {} }
}
}
}
}
}
}
</script>
最佳答案
据我了解,只有当 checked
为 true 时,您才希望 total_hour
成为必填字段。 Vuelidate 为此提供了一个很好的内置验证器,称为 requiredIf
。这是一个contextified validator这样您就可以引用同级属性。
import { required, requiredIf, minLength } from 'vuelidate/lib/validators';
export default {
...
validations: {
timesheet: {
items: {
required,
minLength: minLength(1),
$each: {
total_hour: {
required: requiredIf('checked'),
},
},
},
},
},
}
我在代码中看到的另一个问题是您试图迭代 $v 字段。 $v 字段用于获取字段的验证状态,您不应该设置 $v 字段。将它们用作组件的 v-model 将使 vue 设置 $v 字段。试试这个:
<tr v-for="(item, i) in timesheet.items">
关于javascript - 使用 v-model 的值作为 if 语句的条件是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69081312/