[英]How do I use vuelidate with an array of objects?
我有一組對象,我在表單調查表中循環遍歷這些對象。 每個 object 中有五個屬性,但只有一個屬性需要驗證。 我將組件的驗證部分設置如下:
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: []
}
}
但是,然后我收到以下控制台錯誤“無法讀取未定義的屬性 $model”。 當我 console.log $v.specificGifts.$each.$iter 時,我也會收到控制台錯誤。 有誰知道我做錯了什么? 有沒有更好的方法來使用驗證? 看來 vuelidate 可能跟不上速度,因為它需要我對 $v 屬性進行硬編碼循環,以便無論如何我都可以使用 vuelidate。
我一直在面對一項調查的驗證,並想分享我的解決方案。
我的具體情況是我有很多問題,其中任何一個都有很多答案(一組單選按鈕)。 我的目標是驗證每個問題,以便每個問題都必須檢查一個收音機。
首先,我從 API 得到問題對象數組(我的“值”屬性不同):
[
{
"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,
}
...
]
我使用類星體框架作為模板,但我認為您可以使用基本的 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
}
}
}
}
我在使用 Vuelidate 時也遇到了很多麻煩。 我能給您的最佳解決方案是從Vuelidate更改為VeeValidate 。
更改並不復雜,從長遠來看,它將為您節省大量時間。
VeeValidate 提供了許多使用驗證的簡單方法,包括每個規則的自定義消息(不再計算給出錯誤消息),並允許您根據特定條件使用規則。
您可以在此處查看文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.