vue实现搜索下拉
Vue 实现搜索下拉功能
基础实现思路
使用Vue的v-model绑定输入框数据,结合v-for渲染下拉选项列表。通过监听输入事件触发搜索逻辑,动态显示或隐藏下拉框。
<template>
<div class="search-dropdown">
<input
v-model="searchText"
@input="handleSearch"
@focus="showDropdown = true"
placeholder="输入搜索内容"
/>
<ul v-show="showDropdown && filteredOptions.length">
<li
v-for="item in filteredOptions"
:key="item.id"
@click="selectItem(item)"
>
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchText: '',
showDropdown: false,
options: [], // 原始数据
filteredOptions: [] // 过滤后的数据
}
},
methods: {
handleSearch() {
this.filteredOptions = this.options.filter(item =>
item.name.toLowerCase().includes(this.searchText.toLowerCase())
)
},
selectItem(item) {
this.searchText = item.name
this.showDropdown = false
// 触发选择事件
this.$emit('select', item)
}
}
}
</script>
防抖优化
频繁触发搜索会影响性能,可以使用lodash的debounce函数进行优化。

import { debounce } from 'lodash'
export default {
methods: {
handleSearch: debounce(function() {
this.filteredOptions = this.options.filter(item =>
item.name.toLowerCase().includes(this.searchText.toLowerCase())
)
}, 300)
}
}
键盘导航支持
为提升用户体验,可以添加键盘上下键选择和回车确认功能。
methods: {
handleKeyDown(e) {
if (!this.showDropdown) return
const currentIndex = this.filteredOptions.findIndex(
item => item.name === this.searchText
)
if (e.key === 'ArrowDown') {
const nextIndex = (currentIndex + 1) % this.filteredOptions.length
this.searchText = this.filteredOptions[nextIndex].name
} else if (e.key === 'ArrowUp') {
const prevIndex = (currentIndex - 1 + this.filteredOptions.length) % this.filteredOptions.length
this.searchText = this.filteredOptions[prevIndex].name
} else if (e.key === 'Enter' && currentIndex !== -1) {
this.selectItem(this.filteredOptions[currentIndex])
}
}
}
远程搜索实现
当需要从服务器获取数据时,可以使用axios等库发起请求。

methods: {
handleSearch: debounce(async function() {
try {
const response = await axios.get('/api/search', {
params: { keyword: this.searchText }
})
this.filteredOptions = response.data
} catch (error) {
console.error('搜索失败:', error)
}
}, 500)
}
样式优化
为下拉框添加基础样式提升视觉效果。
.search-dropdown {
position: relative;
width: 300px;
}
.search-dropdown ul {
position: absolute;
width: 100%;
max-height: 200px;
overflow-y: auto;
background: white;
border: 1px solid #ddd;
list-style: none;
padding: 0;
margin: 0;
z-index: 1000;
}
.search-dropdown li {
padding: 8px 12px;
cursor: pointer;
}
.search-dropdown li:hover {
background-color: #f5f5f5;
}
组件化封装
将功能封装为可复用组件,通过props接收配置项。
props: {
options: {
type: Array,
default: () => []
},
placeholder: {
type: String,
default: '请输入'
},
remote: {
type: Boolean,
default: false
},
apiUrl: {
type: String,
default: ''
}
}
这些实现方式可以根据实际需求进行组合和调整,构建出符合项目要求的搜索下拉功能。






