我有一个具有以下结构的对象数组
varientSections: [
{
type: "",
values: [
{
varientId: 0,
individualValue: ""
}
]
}
]
我创建了一个名为isDuplicate的自定义验证,该验证检查属性“ type”的重复值。例如
varientSections: [
{
type: "Basket",
values: [
{
varientId: 0,
individualValue: ""
}
]
},
{
type: "Basket", // ERROR: Duplicate with the "above" object
values: [
{
varientId: 1,
individualValue: ""
}
]
}
],
我能够进行自定义验证。但是,对于数组中存在的所有对象,$ 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
}
}
}
}
}
},
答案 0 :(得分:0)
应该是这样的。
<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>
更改错误类别以适合您的需求。
答案 1 :(得分:0)
我有完全相同的需求,发现只要将头放在要执行的操作上,解决方案就非常简单。仅当当前项目与任何上一个项目重复时,验证器才需要触发。
类似这样的东西:
validations: {
varientSections: {
$each: {
isUnique(currItem, itemArr) {
// Find the index of the first item in the array that has the same type
var firstIdx = itemArr.findIndex((item /*, index, arr*/) => currItem.type === item.type );
// If it's the same as the current item then it is not a duplicte
if(currItem === itemArr[firstIdx])
return true;
// All others are considered duplicates
return false;
},
type: { required }
}
}
}