使用服务器端搜索从 Vuetify 自动完成设置初始值

Set initial value fro Vuetify autocomplete with server site search

我正在使用 v-autocomplete 组件来搜索 google api 上的地点。因此 items 数组在设置搜索输入后得到填充。现在我正在尝试设置一个默认值,以便在用户输入建议火车站之前进行搜索。

例如为城市 London 打开了搜索,现在我不想将搜索输入设置为 London Train Station 以便用户看到以下结果那个搜索。但是,当我将搜索输入设置为默认值时,它每次都会重置为空。

这是我的模板:

    <v-autocomplete
      ref="trainStationSearch"
      v-model="select"
      :items="places"
      :search-input.sync="searchTerm"
      no-filter
      return-object
    >
      <template #item="data">
        <v-list-item-content>
          <v-list-item-title>{{ data.item.title }}</v-list-item-title>
          <v-list-item-subtitle>{{ data.item.subtitle }}</v-list-item-subtitle>
        </v-list-item-content>
      </template>
    </v-autocomplete>

逻辑如下:

  @Prop() readonly prefill?: string

  private places: any = []
  private searchTerm: string | null = ''
  private select: any = null

  private searchGoogle = _.debounce(
    async (val: string, context: Vue): Promise<void> => {
      if (val) {
        // doing the request to my API, which returns the google results
        const data = await apiManager.searchPlaces(val)
        // set the items array to the google results
        this.$set(context, 'places', data.predictions)
      }
    },
    1000
  )

  @Watch('searchTerm')
  private searchPlaces(val: string): void {
    if (val?.trim().length > 0) {
      // trigger debounced request
      this.searchGoogle(val, this)
    } else {
      // empty places array
      this.places.splice(0, this.places.length)
    }
  }

  @Watch('select')
  private handleSelection(): void {
    if (!this.select) {
      return
    }

    // handle selection
  }

  private mounted() {
    if (this.prefill) {
      setTimeout(() => {
        this.searchTerm = this.prefill!
      }, 1000)
    }
  }

我去了官方的 vuetify discord 以获得对此的答案,并发现用我给定的条件重置 search-input 只是预期的行为。考虑到这一点,我试图找出以编程方式设置 search-input 与手动在文本字段中键入以改变 search-input 之间的区别。它是文本字段的焦点。

所以我的解决方法是在设置 searchTerm

之前在自动完成元素上调用 focus()