前端用vue实现搜索
实现 Vue 搜索功能
数据绑定与输入监听
在 Vue 组件中,使用 v-model 双向绑定搜索输入框的值。通过 @input 或 @keyup 事件监听用户输入变化。
<template>
<input v-model="searchQuery" @input="handleSearch" placeholder="搜索...">
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [], // 原始数据列表
filteredItems: [] // 过滤后的结果
}
},
methods: {
handleSearch() {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用计算属性优化性能
对于小型数据集,可以用计算属性替代方法调用,实现自动响应式更新。

computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
添加防抖优化
频繁触发搜索时,通过防抖函数减少请求或计算次数。
methods: {
handleSearch: _.debounce(function() {
this.filteredItems = this.items.filter(item =>
item.name.includes(this.searchQuery)
)
}, 300)
}
服务端搜索实现
当数据量较大时,需要调用 API 接口进行服务端搜索。

methods: {
async handleSearch() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.filteredItems = response.data
} catch (error) {
console.error('搜索出错:', error)
}
}
}
高级搜索功能
实现多条件复合搜索,可以结合多个字段进行过滤。
computed: {
filteredItems() {
return this.items.filter(item => {
const matchesName = item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
const matchesCategory = this.selectedCategory ?
item.category === this.selectedCategory : true
return matchesName && matchesCategory
})
}
}
搜索结果高亮显示
在渲染搜索结果时,对匹配文本进行高亮处理。
<template>
<div v-for="item in filteredItems" :key="item.id">
<span v-html="highlightMatches(item.name)"></span>
</div>
</template>
<script>
methods: {
highlightMatches(text) {
if (!this.searchQuery) return text
const regex = new RegExp(this.searchQuery, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
}
</script>






