vue实现autocomplete
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 组件,可以快速集成:
-
Element UI:
<template> <el-autocomplete v-model="inputValue" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect" ></el-autocomplete> </template> -
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实现方案,可以根据项目需求选择合适的实现方式。







