当前位置:首页 > VUE

vue实现autocomplete

2026-03-06 23:02:37VUE

Vue 实现 Autocomplete 的方法

基础实现(使用原生 HTML 和 Vue 指令)

通过 v-model 绑定输入框的值,利用 v-for 渲染匹配的候选项列表。监听输入事件过滤数据,并通过 v-show 控制下拉列表的显示。

<template>
  <div>
    <input 
      v-model="inputValue" 
      @input="filterOptions"
      @focus="showDropdown = true"
      @blur="handleBlur"
    />
    <ul v-show="showDropdown">
      <li 
        v-for="(option, index) in filteredOptions" 
        :key="index"
        @mousedown="selectOption(option)"
      >
        {{ option }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      options: ['Apple', 'Banana', 'Orange', 'Mango'],
      filteredOptions: [],
      showDropdown: false
    };
  },
  methods: {
    filterOptions() {
      this.filteredOptions = this.options.filter(option =>
        option.toLowerCase().includes(this.inputValue.toLowerCase())
      );
    },
    selectOption(option) {
      this.inputValue = option;
      this.showDropdown = false;
    },
    handleBlur() {
      setTimeout(() => {
        this.showDropdown = false;
      }, 200);
    }
  }
};
</script>

使用第三方库(如 Vue-Awesome-Autocomplete)

安装 vue-awesome-autocomplete 或其他类似库,快速实现功能丰富的自动补全。

npm install vue-awesome-autocomplete
<template>
  <vue-awesome-autocomplete
    v-model="selectedItem"
    :items="items"
    :min-chars="1"
    placeholder="Type to search..."
  />
</template>

<script>
import VueAwesomeAutocomplete from 'vue-awesome-autocomplete';

export default {
  components: {
    VueAwesomeAutocomplete
  },
  data() {
    return {
      selectedItem: '',
      items: ['Red', 'Green', 'Blue', 'Yellow']
    };
  }
};
</script>

远程数据搜索(结合 API 请求)

通过 axios 或其他 HTTP 客户端从远程服务器获取匹配数据,实现动态搜索。

<template>
  <div>
    <input 
      v-model="query" 
      @input="debouncedFetchOptions"
    />
    <ul v-if="suggestions.length">
      <li 
        v-for="(item, index) in suggestions" 
        :key="index"
        @click="selectSuggestion(item)"
      >
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';
import _ from 'lodash';

export default {
  data() {
    return {
      query: '',
      suggestions: []
    };
  },
  created() {
    this.debouncedFetchOptions = _.debounce(this.fetchOptions, 300);
  },
  methods: {
    fetchOptions() {
      if (this.query.trim() === '') {
        this.suggestions = [];
        return;
      }
      axios.get(`/api/search?q=${this.query}`)
        .then(response => {
          this.suggestions = response.data;
        });
    },
    selectSuggestion(item) {
      this.query = item.name;
      this.suggestions = [];
    }
  }
};
</script>

自定义样式与动画

通过 CSS 和 Vue 的过渡组件增强交互体验,如下拉动画和高亮效果。

<template>
  <div class="autocomplete">
    <input v-model="inputText" @input="handleInput" />
    <transition name="fade">
      <ul class="suggestions" v-if="showSuggestions">
        <li 
          v-for="(suggestion, index) in filteredSuggestions"
          :key="index"
          :class="{ active: index === activeIndex }"
          @click="selectSuggestion(suggestion)"
        >
          {{ suggestion }}
        </li>
      </ul>
    </transition>
  </div>
</template>

<style>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
.suggestions li.active {
  background-color: #f0f0f0;
}
</style>

键盘导航支持

通过监听键盘事件(如 ArrowUpArrowDownEnter)增强可访问性。

vue实现autocomplete

methods: {
  handleKeyDown(e) {
    if (e.key === 'ArrowDown') {
      this.activeIndex = Math.min(this.activeIndex + 1, this.filteredSuggestions.length - 1);
    } else if (e.key === 'ArrowUp') {
      this.activeIndex = Math.max(this.activeIndex - 1, 0);
    } else if (e.key === 'Enter') {
      this.selectSuggestion(this.filteredSuggestions[this.activeIndex]);
    }
  }
}

注意事项

  • 性能优化:对于大数据集,使用虚拟滚动(如 vue-virtual-scroller)避免渲染所有候选项。
  • 防抖处理:远程搜索时通过 lodash.debounce 减少请求频率。
  • 无障碍:确保组件支持屏幕阅读器,可通过 aria-* 属性完善。
  • 移动端适配:触屏事件需额外处理,避免与 blur 事件冲突。

标签: vueautocomplete
分享给朋友:

相关文章

vue优秀实现

vue优秀实现

Vue.js 优秀实现方法 响应式数据管理 使用 Vue 的 ref 和 reactive 处理基础类型和对象类型数据,结合 computed 计算属性优化渲染性能。对于复杂状态,推荐 Pinia 替…

vue实现input

vue实现input

Vue 实现 Input 输入框的方法 基本双向绑定 使用 v-model 指令实现双向数据绑定,适用于大多数表单场景: <template> <input v-model="…

vue实现treeselect

vue实现treeselect

Vue TreeSelect 实现方法 使用 Vue 实现 TreeSelect 组件可以通过以下几种方式完成,包括使用现成的第三方库或自行封装组件。 使用第三方库 推荐使用成熟的第三方 TreeS…

vue实现addclass

vue实现addclass

Vue 实现动态添加 class 的方法 在 Vue 中动态添加 class 可以通过多种方式实现,以下是常见的几种方法: 使用对象语法 通过绑定一个对象到 :class,可以动态切换 class…

vue实现Pop

vue实现Pop

Vue 实现 Popover 组件的方法 使用 Vue 内置指令 v-show/v-if 和事件监听 通过 Vue 的指令和事件绑定实现基础的 Popover 功能。定义一个布尔值控制 Popover…

vue原生实现

vue原生实现

Vue 原生实现方法 在 Vue 中实现原生功能通常指直接使用 Vue 的核心特性(如指令、响应式数据、组件等)而非依赖第三方库。以下是几种常见场景的原生实现方式: 数据绑定与响应式更新 Vue 的…