You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止v-autocomplete选中选项时同步搜索触发重复API请求

方案1:Watcher逻辑过滤(改造成本最低)

选中选项时search被赋值为对应条目的name,这个值必然已经存在于你之前请求返回的entries数组的name字段中,直接在watcher开头加过滤判断即可:

watch: {
  filter: {
    handler() {
      this.getDataFromApi();
    },
    deep: true,
  },
  search(val) {
    // 新增判断:值为空/加载中/值已在现有选项中时,不触发请求
    if (!val || this.isLoading || this.entries.some(item => item.name === val)) return;

    this.isLoading = true;
    axios
      .get("/user/worktimes/get-sites", {
        params: {
          keyword: val,
        },
      })
      .then((res) => {
        this.count = res.data.data.sites.length;
        this.entries = res.data.data.sites;
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => (this.isLoading = false));
  },
},

该方案不需要修改模板代码,选中时触发的search更新会被直接拦截,用户后续修改搜索词时也能正常触发新请求。


方案2:修改组件绑定逻辑,阻止选中修改search值

如果需要完全避免选中操作修改search,可以去掉:search-input.sync的双向绑定,手动区分输入事件和选中事件处理:
首先修改模板代码:

<v-autocomplete
            v-model="filter.search"
            :items="entries"
            :loading="loading"
            <!-- 去掉sync修饰符,改为单向绑定 -->
            :search-input="search"
            <!-- 手动监听输入更新search -->
            @update:search-input="val => search = val"
            <!-- 监听选中事件 -->
            @change="onSelect"
            hide-selected
            item-text="name"
            item-value="id"
            label="顧客・現場名"
            solo
            dense
            hide-details
            no-data-text="データがありません"
></v-autocomplete>

新增选中处理方法:

methods: {
  onSelect() {
    // 选中后清空search,彻底避免后续触发不必要的请求
    this.search = ''
  }
}

内容的提问来源于stack exchange,提问作者Nadiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:51:01