vue实现搜索下拉
Vue 实现搜索下拉功能
搜索下拉功能通常结合输入框和下拉列表,实现实时搜索和选择。以下是基于 Vue 的实现方法。
基本结构
使用 Vue 的 v-model 绑定输入框,监听输入变化触发搜索逻辑。
<template>
<div class="search-dropdown">
<input
v-model="searchText"
@input="handleInput"
@focus="showDropdown = true"
placeholder="输入搜索内容"
/>
<ul v-show="showDropdown && filteredItems.length > 0">
<li
v-for="item in filteredItems"
:key="item.id"
@click="selectItem(item)"
>
{{ item.name }}
</li>
</ul>
</div>
</template>
数据与逻辑
定义搜索文本、下拉列表状态和过滤逻辑。
<script>
export default {
data() {
return {
searchText: '',
showDropdown: false,
items: [
{ id: 1, name: '选项1' },
{ id: 2, name: '选项2' }
],
filteredItems: []
}
},
methods: {
handleInput() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchText.toLowerCase())
);
},
selectItem(item) {
this.searchText = item.name;
this.showDropdown = false;
}
}
}
</script>
样式优化
添加基础样式提升用户体验。
<style scoped>
.search-dropdown {
position: relative;
width: 200px;
}
input {
width: 100%;
padding: 8px;
}
ul {
position: absolute;
width: 100%;
border: 1px solid #ccc;
max-height: 200px;
overflow-y: auto;
margin: 0;
padding: 0;
list-style: none;
background: white;
}
li {
padding: 8px;
cursor: pointer;
}
li:hover {
background: #f0f0f0;
}
</style>
高级功能扩展
- 防抖处理:减少频繁搜索请求,使用
lodash.debounce。 - 异步搜索:通过 API 获取搜索结果,结合
axios或fetch。 - 键盘导航:监听键盘事件实现上下选择。
import debounce from 'lodash.debounce';
export default {
methods: {
handleInput: debounce(function() {
this.filterItems();
}, 300)
}
}
通过以上步骤,可以实现一个基础的 Vue 搜索下拉功能,并根据需求扩展高级特性。







