vue 实现搜索
实现 Vue 搜索功能
在 Vue 中实现搜索功能通常涉及以下几个关键步骤:
数据绑定与输入监听
使用 v-model 双向绑定搜索输入框的值,监听用户输入:
<template>
<input v-model="searchQuery" placeholder="搜索..." />
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [] // 原始数据列表
}
}
}
</script>
计算属性实现过滤
通过计算属性实时过滤数据,避免直接修改原始数据:
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
显示过滤结果
在模板中渲染过滤后的结果:
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
优化性能(防抖)
对于大型数据集,建议添加防抖功能:
import { debounce } from 'lodash'
methods: {
handleSearch: debounce(function() {
// 执行搜索逻辑
}, 300)
}
服务端搜索(可选)
如果需要从API获取搜索结果:
methods: {
async fetchSearchResults() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.items = response.data
} catch (error) {
console.error(error)
}
}
},
watch: {
searchQuery(newVal) {
if (newVal.length > 2) {
this.fetchSearchResults()
}
}
}
样式优化
添加加载状态和空状态提示:
<div v-if="loading">搜索中...</div>
<div v-else-if="filteredItems.length === 0">无匹配结果</div>
这些方法可以根据具体需求组合使用,实现从简单到复杂的各种搜索场景。







