代码之家  ›  专栏  ›  技术社区  ›  Pianoc

[Vue warn]:检测到重复的键:x。这可能会导致更新错误。如何防止添加已通过方法添加的项

  •  0
  • Pianoc  · 技术社区  · 5 年前

    我有一个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() {
        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)
    }
    

    0 回复  |  直到 5 年前
        1
  •  1
  •   Evan    5 年前

    你可以使用findIndex

    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 = "";
    }
    
        2
  •  2
  •   Maverick Fabroa    5 年前

    使用检查用户是否存在 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 = ''
    },
    

    或者使用for each loop:

    ...
    
    this.speakers.forEach(function(speaker) {
      if (this.speakers[i].id === newSpeaker.id) {
        // Show an error that the user does already exists
    
        doesUserExists = true;
    
        return;
      }
    });
    
    ...