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

Vue3中如何将搜索下拉选中项添加至新数组并解决点击失效问题

问题解决方案

核心问题分析

  1. @blur 事件触发时机冲突:点击下拉项时,输入框先失去焦点触发 @blur 隐藏下拉列表,导致点击事件来不及执行。
  2. 选中逻辑错误:当前 select 函数传入的是事件对象而非水果名称,且未正确操作响应式数组 selected。
  3. 多余的事件阻止:@click.stop 无实际作用,反而可能干扰事件传递。

修正后的代码

<template>
  <input
    type="text"
    v-model="input"
    placeholder="Search fruits..."
    <!-- 延迟隐藏下拉,给点击事件留执行时间 -->
    @blur="() => setTimeout(() => optionsVisible = false, 100)"
    @input="optionsVisible = true"
  />
  <!-- 移除多余的 @click.stop -->
  <div
    class="item fruit"
    v-if="optionsVisible"
    v-for="fruit in filteredList()"
    :key="fruit"
  >
    <!-- 点击时传入当前水果名称 -->
    <p @click="select(fruit)">{{ fruit }}</p>
  </div>
  <div class="item error" v-if="input && !filteredList().length">
    <p>No results found!</p>
  </div>
  <div class="selected">Selected: {{ selected }}</div>
</template>

<script setup>
import { ref } from 'vue';
let input = ref('');
let optionsVisible = ref(false);
let selected = ref([]);    
// 修改选中逻辑,接收水果参数并操作响应式数组
let select = (fruit) => {
  // 可选:防止重复添加
  if (!selected.value.includes(fruit)) {
    selected.value.push(fruit);
  }
};
const fruits = ['apple', 'banana', 'orange'];
function filteredList() {
  return fruits.filter((fruit) =>
    fruit.toLowerCase().includes(input.value.toLowerCase())
  );
}
</script>

关键修改说明

  • 延迟隐藏下拉列表:通过 setTimeout 给 optionsVisible = false 添加 100ms 延迟,确保点击下拉项的事件能在列表隐藏前执行。
  • 修正选中逻辑:点击下拉项时传入对应的水果名称,在 select 函数中操作 selected.value(响应式 ref 必须通过 .value 访问内部值),同时可添加重复判断避免重复选中。
  • 移除无效事件阻止:删除 @click.stop,消除不必要的事件干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:53:11