vue搜索功能实现
Vue 搜索功能实现
在 Vue 中实现搜索功能通常涉及以下几个关键步骤:
数据绑定与输入监听
使用 v-model 绑定输入框的值到 Vue 实例的数据属性,监听用户输入变化:
<template>
<input v-model="searchQuery" placeholder="搜索..." />
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
}
}
</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 searchItems() {
try {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.filteredItems = response.data
} catch (error) {
console.error(error)
}
}
},
watch: {
searchQuery(newVal) {
if (newVal.length > 2) {
this.searchItems()
}
}
}
高级搜索功能
实现多条件复合搜索:
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
})
}
}
搜索历史记录
添加搜索历史功能:
data() {
return {
searchHistory: []
}
},
methods: {
performSearch() {
if (this.searchQuery.trim()) {
this.searchHistory.unshift(this.searchQuery)
// 限制历史记录数量
if (this.searchHistory.length > 5) {
this.searchHistory.pop()
}
}
}
}






