vue实现列表搜索
实现列表搜索的基本思路
在Vue中实现列表搜索功能,通常需要结合v-model绑定搜索关键词,通过计算属性或方法过滤原始数据。核心是监听输入变化并实时更新展示结果。
基础实现方法
创建Vue实例或组件,定义数据列表和搜索关键词
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
}
使用计算属性实现过滤逻辑
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query)
)
}
}
模板部分绑定数据和展示结果

<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
多字段搜索扩展
当需要搜索多个字段时,调整过滤逻辑
computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query) ||
item.description.toLowerCase().includes(query)
)
}
}
使用自定义过滤方法
对于复杂搜索逻辑,可以使用方法替代计算属性

methods: {
filterItems(query) {
return this.items.filter(item =>
// 自定义过滤条件
)
}
}
添加搜索延迟优化
通过lodash的debounce减少频繁触发
import { debounce } from 'lodash'
methods: {
search: debounce(function(query) {
// 执行搜索
}, 300)
}
服务器端搜索实现
当数据量较大时,建议使用后端搜索API
methods: {
async searchItems() {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.filteredItems = response.data
}
}
样式和交互增强
添加加载状态和空结果提示
<div v-if="loading">Searching...</div>
<div v-else-if="filteredItems.length === 0">
No results found
</div>
完整组件示例
<template>
<div>
<input
v-model="searchQuery"
@input="onSearch"
placeholder="Search items..."
>
<ul v-if="!loading">
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} - {{ item.price }}
</li>
</ul>
<p v-if="loading">Loading...</p>
<p v-if="!loading && filteredItems.length === 0">
No items match your search
</p>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
loading: false,
allItems: [],
filteredItems: []
}
},
async created() {
this.loading = true
this.allItems = await fetchItems()
this.filteredItems = this.allItems
this.loading = false
},
methods: {
onSearch() {
this.loading = true
this.filteredItems = this.allItems.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
item.description.toLowerCase().includes(this.searchQuery.toLowerCase())
)
this.loading = false
}
}
}
</script>






