我的 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)
}
}
}
}
}
},
仍然不断收到错误。请问有什么想法吗?