首页 > 解决方案 > 如何将 vuelidate 与对象数组一起使用?

问题描述

我有一组对象,我在表单调查表中循环遍历这些对象。每个对象中有五个属性,但只有一个属性需要验证。我将组件的验证部分设置如下:

specificGifts: {
      $each: {
        passThrough: {
          required: requiredIf(function(value) {
            return this.docs.includes('Will')
          })
        }
      }
    },

我在我的表单 html 中看到 vuelidate 文档,而不是执行以下代码:

<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。

标签: javascriptvue.jsvuelidate

解决方案


我一直在面对一项调查的验证,并想分享我的解决方案。

我的具体情况是我有很多问题,其中任何一个都有很多答案(一组单选按钮)。我的目标是验证每个问题,以便每个问题都必须检查一个收音机。

首先,我从 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
      }
    }
  }
}

推荐阅读