我有一个v-autocomplete循环用户列表。然后通过btn将它们添加到一个新列表中。如何通过比较dup键来停止并提醒用户已经添加?
<v-autocomplete
v-model="event.user"
:items="usersData"
label="Seach speaker list"
:search-input.sync="searchUser"
return-object
item-value="id"
item-text="name"
></v-autocomplete>
我的addSpeaker方法是:
addSpeaker() {
const newSpeaker = {
id: this.event.user.uid,
name: this.event.user.name,
}
this.speakers.push(newSpeaker)
this.event.user = ''
},
removeSpeaker(id) {
this.speakers = this.speakers.filter(speaker => speaker.id !== id)
}
我可以在这里做一个检查来防止一个已经添加的用户被添加吗?
使用id
检查用户是否存在。如果用户存在,则显示错误,否则添加用户:
addSpeaker () {
const newSpeaker = {
id: this.event.user.uid,
name: this.event.user.name,
}
let doesUserExists = false;
for (let i = 0; i < this.speakers.length; i++) {
if (this.speakers[i].id === newSpeaker.id) {
// Show an error that the user does already exists
doesUserExists = true;
break;
}
}
if (!doesUserExists) {
this.speakers.push(newSpeaker);
}
this.event.user = ''
},
或在每个循环中使用:
...
this.speakers.forEach(function(speaker) {
if (this.speakers[i].id === newSpeaker.id) {
// Show an error that the user does already exists
doesUserExists = true;
return;
}
});
...
可以使用findinindex
addSpeaker() {
const newSpeaker = {
id: this.event.user.uid,
name: this.event.user.name
};
const check = this.speakers.findIndex(x => x.name == this.event.user.name) === -1;
check && this.speakers.push(newSpeaker);
this.event.user = "";
}