在 v-for 循环中使用 v-autocomplete 会导致死循环

Using v-autocomplete in a v-for loop results in a endless loop

我有以下设置:

<template>
  <div>
  <div v-for="(participant, i) in participants" :key="`participant-${i}`">
   <v-autocomplete
     label="Search person"
     v-model="selected_persons[i]"
     outlined
     dense
     return-object
     cache-items
     :items="persons"
     @change="event => someMethod(event, i)"
     :search-input.sync="person"
     item-text="full_name"
     item-value="person_id"
     hide-details
   />
  </div>
</div>
</template>

<script>
export default {
data()
{
  return {
    person: null,
    persons: [],
    selected_persons: [],
    participants: [
       {
          person_id: 1,
          full_name: 'John Doe'
        },
        {
          person_id: 2,
          full_name: 'Jane Doe'
        }
    ]
  }
},
watch: {
   person(value)
   {
        value && value.length > 2 && this.queryPersons({search: value});
   },
},
methods: {
}
   async queryPersons(search)
   {
      let response = await fetch(route('search.persons', search));
       this.persons = await response.json();
     },
}
</script>

当自动完成同时用于 participants 时,这将导致 update:search-input 的无限循环。这里真正的问题似乎是您无法向 :search-input.sync="person" 添加索引。所以我的问题是如何在 v-for 循环中使用自动完成功能。

您可以在 @update:search-input 事件上使用数组和方法,而不是使用观察器,如下所示:

<template>
  <div>
  <div v-for="(participant, i) in participants" :key="`participant-${i}`">
   <v-autocomplete
        label="Person search"
        v-model="selected_persons[i]"
        outlined
        dense
        return-object
        cache-items
       :items="persons"
       @change="event => addPersonToPossibleParticipants(event, i)"
       :search-input.sync="person && person.length > 0 ? person[i] : null"
        @update:search-input="event => searchPerson(event, i)"
        item-text="full_name"
        item-value="person_id"
        hide-details
   />
  </div>
</div>
</template>

<script>
export default {
data()
{
  return {
    person: null,
    persons: [],
    selected_persons: [],
    participants: [
       {
          person_id: 1,
          full_name: 'John Doe'
        },
        {
          person_id: 2,
          full_name: 'Jane Doe'
        }
    ]
  }
},
methods: {
}
   async queryPersons(search)
   {
      let response = await fetch(route('search.persons', search));
       this.persons = await response.json();
     },

     searchPerson(value, index)
     {
        this.person[index] = value;

        if(value && value.length > 2) {
          this.queryPersons({search: value});
        }
      },
}
</script>