问题描述
如何将 v-model="item.checked"
作为 if
的条件放在下面的 validations()
?
<tr v-for=(item, i) of $v.timesheet.items.$each.$iter";><div><td></tr><tr><div><td><按钮类型=按钮"class =btn btn-sm btn-primary"@click="itemCount++";>添加行</td>
</tr>
据我所知,只有在 checked
为真时,您才希望 total_hour
成为必填字段.Vuelidate 为此提供了一个很好的内置验证器,称为 requiredIf
.它是一个上下文验证器,因此您可以引用同级属性.
import { required, requiredIf, minLength } from 'vuelidate/lib/validators';导出默认{...验证:{时间表: {项目: {必需的,minLength: minLength(1),$每个:{总小时:{要求:requiredIf('checked'),},},},},},}
我在您的代码中看到的另一个问题是您试图遍历 $v 字段.$v 字段用于获取字段的验证状态,您不应该设置 $v 字段.将它们用作组件的 v-model
将使 vue 设置 $v 字段.试试这个:
How do I put the v-model="item.checked"
as the condition of the if
in below validations()
?
<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>
So as I understand, you want total_hour
to be a required field only if checked
is true. Vuelidate provides a nice built-in validator for this purpose called requiredIf
. It is a contextified validator so you can reference a sibling property.
import { required, requiredIf, minLength } from 'vuelidate/lib/validators';
export default {
...
validations: {
timesheet: {
items: {
required,
minLength: minLength(1),
$each: {
total_hour: {
required: requiredIf('checked'),
},
},
},
},
},
}
Another problem I see in your code is that you're trying to iterate over $v fields. $v fields are used to get validation states for your fields, you're not supposed to set $v fields. Using them as v-model
for components will make vue set the $v fields. Try this:
<tr v-for="(item, i) in timesheet.items">
这篇关于使用 v-model 的值作为 if 语句的条件是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!