vue实现搜索
Vue 实现搜索功能
在 Vue 中实现搜索功能通常涉及数据绑定、事件监听和过滤逻辑。以下是几种常见的实现方式:
使用计算属性过滤列表
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用 watch 监听搜索输入
<script>
export default {
data() {
return {
searchQuery: '',
items: [],
filteredItems: []
}
},
watch: {
searchQuery(newVal) {
this.filterItems(newVal)
}
},
methods: {
filterItems(query) {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
)
}
},
created() {
// 初始化数据
this.items = [...]
this.filteredItems = [...this.items]
}
}
</script>
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以使用 lodash 的防抖功能优化性能:
import { debounce } from 'lodash'
export default {
methods: {
search: debounce(function(query) {
// 执行搜索逻辑
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
)
}, 300)
}
}
与服务端交互的搜索
当数据量较大时,通常需要后端配合实现搜索:
methods: {
async searchItems() {
try {
const response = await axios.get('/api/items', {
params: {
q: this.searchQuery
}
})
this.filteredItems = response.data
} catch (error) {
console.error(error)
}
}
}
搜索功能优化建议
- 添加加载状态指示器
- 实现空结果提示
- 考虑添加搜索历史功能
- 对于移动端,优化键盘体验
- 添加搜索按钮触发事件
以上方法可以根据具体需求组合使用,计算属性方式适合前端过滤简单数据,而服务端搜索适合处理大量数据。







