
本文深入探讨了在vue自定义多选组件中处理焦点事件的常见问题。当组件内部输入框失去焦点时,外部容器的blur事件可能无法按预期触发,导致下拉列表无法关闭。核心问题在于blur事件不冒泡,而focusout事件则会冒泡。通过将blur替换为focusout,并确保容器可聚焦,可以有效解决此问题,实现组件外部点击时正确关闭选项列表的功能。
在开发Vue自定义组件,特别是像多选下拉列表这类需要根据焦点状态控制UI元素(如选项列表)显示与隐藏的组件时,正确处理焦点事件至关重要。一个常见的需求是,当用户点击组件外部时,组件的选项列表应该自动关闭。开发者通常会尝试在组件的根元素上监听blur事件来实现这一逻辑。然而,在某些情况下,尤其当组件内部包含可聚焦的元素(如input字段)时,blur事件的行为可能不尽如人意。
具体来说,如果用户点击组件内部的input字段,然后点击组件外部的任何地方,组件根元素上的blur事件可能不会触发,导致选项列表仍然保持打开状态。这通常是由于对浏览器事件机制的误解造成的。
要理解上述问题并找到解决方案,我们需要深入理解blur和focusout这两个焦点相关事件的本质区别:
blur事件:
立即学习“前端免费学习笔记(深入)”;
focusout事件:
鉴于blur事件不冒泡的特性,为了在父元素上捕获其子元素失去焦点的事件,我们应该使用focusout事件。
原始代码中的问题示例:
<div @blur="showOptions = false" :tabindex="tabIndex"> <!-- ... 组件内容,包括一个input字段 ... --> <input class="focus:outline-0 w-full" type="text" v-model="searchInput" /> <!-- ... --> </div>
在这个例子中,@blur="showOptions = false"绑定在外部div上。当用户在input字段中输入后,点击组件外部,input字段会失去焦点。但由于blur事件不冒泡,外部div不会收到这个失去焦点的通知,showOptions也就不会被设置为false。
修正后的代码示例:
将外部div上的@blur事件替换为@focusout。
<template>
  <div class="flex flex-col relative w-full">
    <span v-if="label" class="font-jost-medium mb-2">{{ label }}</span>
    <div>
      <!-- 将 @blur 替换为 @focusout -->
      <div @focusout="showOptions = false" :tabindex="tabIndex">
        <div
          class="border border-[#EAEAEA] bg-white rounded-md flex flex-col w-full"
        >
          <div
            v-if="selectedOptions.length"
            class="flex flex-wrap px-4 py-2 border-b gap-2"
          >
            <div
              v-for="option in selectedOptions"
              class="border bg-secondary rounded-full py-1 px-2 flex items-center"
            >
              <span>{{ option.text }}</span>
              <vue-feather
                type="x"
                class="h-3 w-3 ml-1.5 cursor-pointer"
                @click="onDeleteOption(option)"
              />
            </div>
          </div>
          <div
            class="flex flex-row justify-end items-center px-4 cursor-pointer"
            :class="selectedOptions.length ? 'py-2' : 'p-4'"
            @click="showOptions = !showOptions"
          >
            <MagnifyingGlassIcon class="h-5 w-5 mr-2" />
            <input
              class="focus:outline-0 w-full"
              type="text"
              v-model="searchInput"
            />
            <vue-feather type="chevron-down" class="h-5 w-5" />
          </div>
        </div>
        <div v-if="showOptions && optionsMap.length" class="options-list">
          <ul role="listbox" class="w-full overflow-auto">
            <li
              class="hover:bg-primary-light px-4 py-2 rounded-md cursor-pointer"
              role="option"
              v-for="option in optionsMap"
              @mousedown="onOptionClick(option)"
            >
              {{ option.text }}
            </li>
          </ul>
        </div>
        <div
          id="not-found"
          class="absolute w-full italic text-center text-inactive-grey"
          v-else-if="!optionsMap.length"
        >
          No records found
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, PropType, ref, watch } from "vue";
import { MagnifyingGlassIcon } from "@heroicons/vue/24/outline";
export default defineComponent({
  name: "AppAutocomplete",
  components: {
    MagnifyingGlassIcon,
  },
  props: {
    modelValue: {
      type: String,
    },
    label: {
      type: String,
      default: "",
    },
    tabIndex: {
      type: Number,
      default: 0, // 确保父div可聚焦
    },
    options: {
      type: Array as PropType<{ text: string; value: string }[]>,
      required: true,
    },
  },
  setup(props, { emit }) {
    const showOptions = ref(false);
    const optionsMap = ref(props.options);
    const selectedOptions = ref<{ text: string; value: string }[]>([]);
    const searchInput = ref("");
    watch(searchInput, () => {
      optionsMap.value = props.options.filter((option1) => {
        return (
          !selectedOptions.value.some((option2) => {
            return option1.text === option2.text;
          }) &&
          option1.text.toLowerCase().includes(searchInput.value.toLowerCase())
        );
      });
      sortOptionsMapList();
    });
    const onOptionClick = (option: { text: string; value: string }) => {
      searchInput.value = "";
      selectedOptions.value.push(option);
      optionsMap.value = optionsMap.value.filter((option1) => {
        return !selectedOptions.value.some((option2) => {
          return option1.text === option2.text;
        });
      });
      sortOptionsMapList();
      emit("update:modelValue", option.value);
    };
    const onDeleteOption = (option: { text: string; value: string }) => {
      selectedOptions.value = selectedOptions.value.filter((option2) => {
        return option2.text !== option.text;
      });
      optionsMap.value.push(option);
      sortOptionsMapList();
    };
    const sortOptionsMapList = () => {
      optionsMap.value.sort(function (a, b) {
        return a.text.localeCompare(b.text);
      });
    };
    sortOptionsMapList();
    return {
      showOptions,
      optionsMap,
      searchInput,
      selectedOptions,
      onOptionClick,
      onDeleteOption,
    };
  },
});
</script>
<style scoped lang="scss">
.options-list,
#not-found {
  box-shadow: 0 0 50px 0 rgb(19 19 28 / 12%);
  @apply border border-[#EAEAEA] rounded-md p-4 mt-1 absolute bg-white z-10 w-full;
}
ul {
  @apply max-h-52 #{!important};
}
</style>在Vue自定义组件中,当需要父元素监听其内部子元素失去焦点的事件时,应优先使用focusout事件而非blur事件。focusout事件的冒泡特性使其能够捕获到子元素失去焦点的通知,从而实现更灵活和可靠的UI交互逻辑。同时,确保父容器具有tabindex属性是实现这一机制的必要条件。通过这些调整,可以显著提升自定义多选组件的用户体验和功能完整性。
以上就是Vue自定义多选组件中焦点事件处理:Blur与Focusout的深度解析的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号