1

我的 Vue 文件中有以下结构的数据:

data() {
  return {
    formData: {
      name: 'foo',
      objects: [
        {id: 0, name: 'a', props: []},
        {id: 1, name: 'b', props: ['2', '23']},
        {id: 2, name: 'c', props: ['44']},
        {id: 3, name: 'd', props: []}
      ]
    },
    currentObj = null,
    currentPropIndex = null
  }
}

数组中的对象数量是动态的,数组objects也是动态的props,其中可以添加和删除字符串值。我需要使用 Vuelidate 在每个对象更改时验证每个对象中的 props 数组的每个值。所以我尝试了这个:

validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      props: {
        $each: {
          required, numeric, maxLength: maxLength(5)
        }
      }
    }
  }
},

计算:

propsErrors() {
    const errors = [];
    if ( this.currentObj) {
      // const objIndex = _.findIndex(this.formData.objects, o => o.id === this.currentObj.id)
      if (!this.$v.formData.objects['props'][this.currentPropIndex].$dirty) {
        return errors;
      }
      !this.$v.formData.objects['props'][this.currentPropIndex].maxLength && errors.push('Max 5 digits')
      !this.$v.formData.objects['props'][this.currentPropIndex].required && errors.push('Required')
      !this.$v.formData.objects['props'][this.currentPropIndex].numeric && errors.push('Digits only')
    }
    return errors
  },

还有我的 Vuetify 文本字段:

<v-text-field single-line flat dense required
  v-model="object.props[index]"
  :error-messages="propsErrors"
  label="Prop"
  height="30"
  @click="setCurrents(protocol, index)"
  @blur="$v.formData.protocolPorts['manual_ports'][index].$touch()"
  @input="$v.formData.protocolPorts['manual_ports'][index].$touch()" />

并且setCurrents只设置当前编辑的对象和道具索引:

setCurrents (protocol, index) {
    this.currentObj = protocol;
    this.currentPropIndex = index;
  }

一旦我测试页面并单击文本字段,我就会收到此错误:Error in render: "TypeError: Cannot read property 'props' of undefined"

我试图改变propsErrors(objIndex目前在上面的代码中被注释掉了)

this.$v.formData.objects[objIndex]['props'][index].maxLength && errors.push('Max 5 digits')

文本字段(oi代表对象索引):

@input="$v.formData.objects[oi].props[index].$touch()"

和验证:

validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      required,
      $each: {
        props: {
          $each: {
            required, numeric, maxLength: maxLength(5)
          }
        }
      }
    }
  }
},

仍然不断收到错误。请问有什么想法吗?

4

2 回答 2

0

$each 现在已删除,请参阅此https://github.com/vuelidate/vuelidate/issues/781

于 2021-09-28T03:51:41.040 回答
0

我从未使用过 Vuelidate,但我发现这个示例非常有用,并且与您尝试执行的操作相当相似https://vuelidate.js.org/#sub-collections-validation

您在 Vue 实例中的数据应该从

currentObj = null,
currentPropIndex = null

currentObj: null,
currentPropIndex: null
于 2020-02-19T13:14:49.773 回答