Iss*_*aki 5 javascript vue.js vuelidate
我有一个具有以下结构的对象数组
varientSections: [
{
type: "",
values: [
{
varientId: 0,
individualValue: ""
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
我创建了一个名为 isDuplicate 的自定义验证,它检查属性“type”的重复值。例如
varientSections: [
{
type: "Basket",
values: [
{
varientId: 0,
individualValue: ""
}
]
},
{
type: "Basket", // ERROR: Duplicate with the "above" object
values: [
{
varientId: 1,
individualValue: ""
}
]
}
],
Run Code Online (Sandbox Code Playgroud)
我能够让我的自定义验证工作。但是,对于数组中存在的所有对象,$invalid 属性将为 false。因此,数组中的所有对象都将以红色突出显示
下面是我的验证代码:
validations: {
varientSections: {
$each: {
type: {
required,
isDuplicate(type, varient) {
console.log(varient);
const varientIndex = this.varientSections.findIndex(
v => v.type === type
);
var isWrong = true;
this.varientSections.forEach((varObject, index) => {
if (index !== varientIndex) {
if (varObject.type === varient.type) {
isWrong = false;
}
}
});
return isWrong;
}
},
values: {
$each: {
individualValue: {
required
}
}
}
}
}
},
Run Code Online (Sandbox Code Playgroud)
应该是这样的。
<div v-for="(vs, index) in varientSections" :key="index">
<input :class="{'is-error': $v.varientSections.$each[index].type.$error}" type="text" v-model="vs.type">
<input :class="{'is-error': $v.varientSections.$each[index].value.$error}" type="text" v-model="vs.value>
</div>
Run Code Online (Sandbox Code Playgroud)
更改错误类别以满足您的需要。