我有一个对象数组,我在表单调查问卷中遍历这些对象。每个对象中有五个属性,但只有一个属性需要验证。我设置了组件的验证部分,如下所示:
specificGifts: {
$each: {
passThrough: {
required: requiredIf(function(value) {
return this.docs.includes('Will')
})
}
}
},我在vuelidate文档上看到,在我的表单html中,而不是执行以下代码:
<div
v-for="(gift, i) in specificGifts"
:key="i"
>
<v-select
label="How does this specific gift pass if the recipient does not survive?"
v-model="gift.passThrough"
:items="specificGiftPassThrough"
></v-select>
</div>我应该使用:
<div
v-for="(gift, i) in $v.specificGifts.$each.$iter"
:key="i"
>
<v-select
label="How does this specific gift pass if the recipient does not survive?"
v-model="gift.passThrough.$model"
:items="specificGiftPassThrough"
></v-select>
</div>我的vuejs组件的数据部分如下:
data(){
return{
specificGifts: []
}
}然而,我得到了下面的控制台错误"Cannot read property $model of undefined“。当我console.log $v.specificGifts.$each.$iter时,我也得到了控制台错误。有人知道我做错了什么吗?有没有更好的方式来使用验证?看起来vuelidate可能跟不上速度,因为它要求我硬编码通过$v属性的循环,这样我就可以使用vuelidate了。
发布于 2020-12-25 18:31:58
我一直在面对一项调查的验证,并想分享我的解决方案。
我的具体情况是我有很多问题,其中任何一个都有很多答案(一组单选按钮)。我的目标是验证每个问题,因此对于每个问题,必须检查一个无线电。
首先,我从API获取对象的问题数组(我的"value“属性是不同的):
[
{
"value":"a",
"name":"first question",
"answers":[
{
"label":"first answer",
"value":"a1"
},
{
"label":"second answer",
"value":"a2"
},
...
]
},
{
"value":"b",
"name":"second question",
"answers":[
{
"label":"first answer",
"value":"b1"
},
{
"label":"second answer",
"value":"b2"
},
...
]
}
...
]然后,在获得API响应后,我为答案准备了另一个对象数组:
this.questions.map(function (item) {
return {
questionId: item.value,
answerId: null
};
})结果就是这个结构:
[
{
questionId: 'a',
answerId: null,
},
{
questionId: 'b',
answerId: null,
}
...
]我使用了quasar框架作为模板,但我认为你可以用基本的html重现这个逻辑:
<q-field v-for="(question, key) in questions" :key="question.value"
filled
:label="question.name"
>
<template v-slot:control>
<q-option-group
v-model="answers[key].answerId"
:options="question.answers"
type="radio"
/>
</template>
</q-field>最后,我的验证规则是:
validations: {
answers: {
$each: {
answerId: {
required
}
}
}
}发布于 2020-06-05 22:43:18
我用Vuelidate也遇到了很多麻烦。我能给你的最好的解决方案是从Vuelidate改为VeeValidate。
更改它并不复杂,从长远来看,它将为您节省大量时间。
VeeValidate提供了许多简单的方法来使用验证,包括为每个规则定制消息(不再计算错误消息),并允许您根据特定条件使用规则。
您可以查看文档here
https://stackoverflow.com/questions/62217573
复制相似问题