当前位置:首页 > 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 实现中台系统的关键步骤 技术选型与基础搭建 使用 Vue 3(Composition API)或 Vue 2(Options API)作为前端框架,搭配 Vue Router 实现路由管理,V…

jq 实现 vue

jq 实现 vue

jq 实现 Vue 的核心功能 jq 是一个轻量级的 JavaScript 库,主要用于 DOM 操作和事件处理。虽然它不能完全替代 Vue,但可以通过一些技巧模拟 Vue 的核心功能,如数据绑定、事…

vue实现打印

vue实现打印

使用Vue实现打印功能 在Vue项目中实现打印功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用window.print() 这种方法适用于打印整个页面或特定区域的内容。 // 在Vu…

vue实现文章滚动

vue实现文章滚动

Vue 实现文章滚动效果 使用 CSS 实现基础滚动 通过 CSS 的 overflow 和 height 属性控制滚动区域,适用于静态内容滚动。在 Vue 模板中定义固定高度的容器,内容超出后自动滚…

vue实现切换隐藏

vue实现切换隐藏

使用 v-show 指令实现切换隐藏 在 Vue 中,v-show 是最简单的切换元素显示/隐藏的方法。它通过 CSS 的 display 属性控制元素可见性。 <template>…

使用ts实现vue

使用ts实现vue

使用 TypeScript 实现 Vue 应用 要在 Vue 项目中使用 TypeScript,可以通过 Vue CLI 或手动配置 TypeScript 环境。以下是具体方法: 通过 Vue CL…