我在那里做了一个简单的小演示->
https://codesandbox.io/s/v81mxn2ojy
在控制台中查看一下,如果我在textfields中写入,验证会被多次调用。如果我在textfields之间切换并更改值,它就会堆积起来。
模板
<p class="sizes__input" v-for="(size, i) in sizes">
<span>Size: </span>
<input
type="text"
:name="`prefix${i}`"
class="textfield max-dim__input"
v-model="size.prefix"
maxlength="8"
autocomplete="off"
v-validate="{ required: true, unique: prefixes }"
:class="{ error: errors.has(`prefix${i}`) }"
/>
</p>
data() {
return {
sizes: [
{ prefix: "xl_", width: "1400", height: "1400" },
{ prefix: "l_", width: "1100", height: "1100" },
{ prefix: "m_", width: "800", height: "800" },
{ prefix: "s_", width: "600", height: "600" },
{ prefix: "thumb_", width: "200", height: "200" }
]
};
},
computed: {
prefixes() {
console.log("prefix");
if (this.sizes) {
return this.sizes.map(item => {
return item.prefix;
});
}
}
}
const unique = {
getMessage(field) {
return `Such ${field} already exists.`;
},
validate(value, args) {
if (value) {
console.log(value, args, args.indexOf(value));
return args.indexOf(value) === -1;
}
return false;
}
};
Validator.extend("unique", unique, {
immediate: false
});
好的找到了解决办法
在focus上,我过滤数据并将其发送给验证器。
输入字段
<input
v-validate="{ required: true, unique: filteredSizes }"
@focus="filterSizes(i);"
data() {
return {
filteredSizes: [],
sizes:
聚焦
filterSizes(i) {
const otherSizes = [...this.sizes];
otherSizes.splice(i, 1);
this.filteredSizes = otherSizes.map(item => {
return item.prefix;
});
}
https://codesandbox.io/s/38qyyymyw5