当前位置:首页 > 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组件添加基本样式:

.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实现方案,可以根据项目需求选择合适的实现方式。

vue实现autocomplete

标签: vueautocomplete
分享给朋友:

相关文章

vue无限菜单怎么实现

vue无限菜单怎么实现

实现 Vue 无限菜单的方法 递归组件实现嵌套菜单 使用 Vue 的递归组件特性可以轻松实现无限级嵌套菜单。通过组件调用自身的方式处理嵌套数据。 <template> <ul&…

vue实现tablegrid

vue实现tablegrid

Vue 实现 TableGrid 的方法 使用 Element UI 的 Table 组件 Element UI 提供了强大的 Table 组件,可以快速实现表格布局。安装 Element UI 后,…

vue实现sso

vue实现sso

Vue 实现 SSO(单点登录)方案 单点登录(SSO)允许用户通过一次登录访问多个相关系统。以下是基于 Vue 的实现方案: 使用 OAuth2/OpenID Connect 协议 OAuth2…

vue菜单实现

vue菜单实现

Vue 菜单实现方法 使用 Element UI 的菜单组件 Element UI 提供了现成的菜单组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用 el-menu 相关组件。…

vue实现引导

vue实现引导

Vue 实现引导功能的方法 使用第三方库 推荐使用 driver.js 或 intro.js 这类专门为 Vue 设计的引导库。这些库提供了完整的 API 和样式,能够快速实现引导功能。 安装 dr…

vue能实现

vue能实现

Vue.js 是一个流行的前端框架,能够实现多种功能。以下是 Vue 能够实现的主要功能和特性: 响应式数据绑定 Vue 的核心特性之一是响应式数据绑定。通过数据驱动视图,当数据发生变化时,视图会自…