vue实现搜索列表

Vue 实现搜索列表
在 Vue 中实现搜索列表功能,通常需要结合数据绑定、计算属性和事件监听。以下是一个完整的实现方案:
数据准备与模板结构
<template>
<div>
<input
v-model="searchQuery"
placeholder="搜索..."
@input="handleSearch"
/>
<ul>
<li v-for="item in filteredList" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
组件脚本部分
<script>
export default {
data() {
return {
searchQuery: '',
originalList: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
computed: {
filteredList() {
return this.originalList.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
},
methods: {
handleSearch() {
// 可以添加防抖逻辑
}
}
}
</script>
优化方案(添加防抖)
import { debounce } from 'lodash';
methods: {
handleSearch: debounce(function() {
// 搜索逻辑已由计算属性自动处理
}, 300)
}
服务端搜索实现
当需要从服务端获取搜索结果时:
methods: {
async fetchSearchResults() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
});
this.filteredList = response.data;
} catch (error) {
console.error(error);
}
}
}
样式增强
<style scoped>
input {
padding: 8px;
width: 200px;
margin-bottom: 16px;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 8px;
border-bottom: 1px solid #eee;
}
</style>
高级功能扩展
- 多条件搜索:可以扩展过滤逻辑,同时匹配多个字段
- 搜索高亮:使用正则表达式匹配搜索关键词并添加样式
- 虚拟滚动:对于大型列表,实现虚拟滚动优化性能
- 搜索历史:本地存储搜索记录
这个实现涵盖了从基础到进阶的搜索列表功能,可以根据实际需求进行适当调整。







