当前位置:首页 > VUE

vue实现autocomplete

2026-02-09 23:12:15VUE

Vue 实现 Autocomplete 功能

Autocomplete(自动完成)是一种常见的用户输入辅助功能,能够根据用户输入提供建议列表。以下是几种在 Vue 中实现 Autocomplete 的方法:

使用原生 HTML 和 Vue 数据绑定

通过结合 Vue 的数据绑定和事件监听,可以快速实现一个基础的 Autocomplete 功能。

<template>
  <div>
    <input 
      v-model="inputValue" 
      @input="handleInput" 
      @focus="showSuggestions = true"
      @blur="hideSuggestions"
    />
    <ul v-if="showSuggestions && filteredSuggestions.length">
      <li 
        v-for="(item, index) in filteredSuggestions" 
        :key="index"
        @mousedown="selectSuggestion(item)"
      >
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
      suggestions: ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'],
      filteredSuggestions: [],
      showSuggestions: false
    }
  },
  methods: {
    handleInput() {
      this.filteredSuggestions = this.suggestions.filter(item =>
        item.toLowerCase().includes(this.inputValue.toLowerCase())
      )
    },
    selectSuggestion(item) {
      this.inputValue = item
      this.showSuggestions = false
    },
    hideSuggestions() {
      setTimeout(() => {
        this.showSuggestions = false
      }, 200)
    }
  }
}
</script>

使用第三方组件库

许多流行的 Vue UI 组件库都提供了现成的 Autocomplete 组件,可以快速集成:

  1. Element UI:

    <template>
    <el-autocomplete
     v-model="inputValue"
     :fetch-suggestions="querySearch"
     placeholder="请输入内容"
     @select="handleSelect"
    ></el-autocomplete>
    </template>
  2. Vuetify:

    <template>
    <v-autocomplete
     v-model="inputValue"
     :items="items"
     :search-input.sync="search"
     clearable
     hide-details
     label="Search"
    ></v-autocomplete>
    </template>

自定义高级 Autocomplete

对于更复杂的需求,可以创建一个自定义的 Autocomplete 组件:

<template>
  <div class="autocomplete">
    <input
      type="text"
      v-model="inputValue"
      @input="onInputChange"
      @keydown.down="onArrowDown"
      @keydown.up="onArrowUp"
      @keydown.enter="onEnter"
    />
    <ul v-show="isOpen" class="suggestions">
      <li
        v-for="(suggestion, index) in matches"
        :key="index"
        @click="selectItem(suggestion)"
        :class="{ 'is-active': index === arrowCounter }"
      >
        {{ suggestion }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    items: {
      type: Array,
      required: false,
      default: () => []
    },
    shouldFilter: {
      type: Boolean,
      required: false,
      default: true
    }
  },
  data() {
    return {
      inputValue: '',
      isOpen: false,
      arrowCounter: -1
    }
  },
  computed: {
    matches() {
      if (!this.shouldFilter) return this.items
      return this.items.filter(item => {
        return item.toLowerCase().includes(this.inputValue.toLowerCase())
      })
    }
  },
  methods: {
    onInputChange() {
      this.isOpen = true
      this.arrowCounter = -1
    },
    onArrowDown() {
      if (this.arrowCounter < this.matches.length - 1) {
        this.arrowCounter++
      }
    },
    onArrowUp() {
      if (this.arrowCounter > 0) {
        this.arrowCounter--
      }
    },
    onEnter() {
      if (this.arrowCounter >= 0) {
        this.selectItem(this.matches[this.arrowCounter])
      }
    },
    selectItem(item) {
      this.inputValue = item
      this.isOpen = false
      this.arrowCounter = -1
      this.$emit('item-selected', item)
    }
  }
}
</script>

异步数据加载

当需要从API获取建议时,可以使用异步方法:

methods: {
  async querySearch(queryString, cb) {
    try {
      const response = await axios.get('/api/search', {
        params: { q: queryString }
      })
      cb(response.data)
    } catch (error) {
      console.error(error)
      cb([])
    }
  }
}

样式优化

为Autocomplete组件添加基本样式:

vue实现autocomplete

.autocomplete {
  position: relative;
}

.suggestions {
  position: absolute;
  z-index: 1000;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  list-style: none;
  padding: 0;
  margin: 0;
  border: 1px solid #eee;
  background: white;
}

.suggestions li {
  padding: 8px 12px;
  cursor: pointer;
}

.suggestions li.is-active,
.suggestions li:hover {
  background-color: #f5f5f5;
}

以上方法提供了从简单到复杂的Vue Autocomplete实现方案,可以根据项目需求选择合适的实现方式。

标签: vueautocomplete
分享给朋友:

相关文章

vue实现裁剪头像

vue实现裁剪头像

Vue 实现头像裁剪功能 实现头像裁剪功能通常需要结合第三方库如 cropperjs 或 vue-cropper。以下是两种常见实现方式: 使用 vue-cropper 库 安装依赖: n…

简单实现vue

简单实现vue

Vue 的基本实现 创建一个简单的 Vue 应用需要引入 Vue 库,并编写基本的模板和数据绑定逻辑。 <!DOCTYPE html> <html lang="en"> &l…

vue实现ide

vue实现ide

Vue 实现 IDE 的基本思路 使用 Vue 构建一个简易的集成开发环境(IDE)需要整合代码编辑器、文件管理、终端模拟等功能。以下是关键实现步骤和推荐工具。 核心功能模块 代码编辑器 使用…

vue最佳实现

vue最佳实现

Vue 最佳实践 组件设计 组件应遵循单一职责原则,每个组件只负责一个功能模块。命名采用 PascalCase(如 UserProfile.vue),模板中使用 kebab-case(如 <us…

vue模版实现

vue模版实现

Vue 模板实现方法 Vue 模板是 Vue.js 的核心特性之一,用于声明式地将 DOM 绑定至底层 Vue 实例的数据。以下是几种常见的 Vue 模板实现方式: 单文件组件(SFC) 使用 .v…

vue实现幻灯

vue实现幻灯

Vue实现幻灯片的基础方法 使用Vue实现幻灯片功能可以通过多种方式完成,以下是几种常见方案: 方案一:基于Vue的过渡动画 通过Vue的<transition>或<transit…