vue中实现搜索查询
实现搜索查询的基本思路
在Vue中实现搜索查询功能通常涉及以下几个核心部分:数据绑定、事件监听、过滤逻辑和界面渲染。以下是具体实现方法:
数据绑定与输入框
使用v-model双向绑定搜索关键词,监听用户输入:
<template>
<input v-model="searchQuery" placeholder="搜索..." />
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
}
}
</script>
计算属性实现过滤
利用计算属性动态过滤数据,避免每次输入都重新计算:
<script>
export default {
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
渲染过滤结果
在模板中展示过滤后的结果:
<template>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>
防抖优化性能
对于大数据量或API请求,建议添加防抖功能:
<script>
import _ from 'lodash'
export default {
data() {
return {
searchQuery: '',
items: [],
allItems: []
}
},
created() {
this.debouncedFilter = _.debounce(this.filterItems, 300)
},
methods: {
filterItems() {
this.items = this.allItems.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
},
watch: {
searchQuery() {
this.debouncedFilter()
}
}
}
</script>
远程搜索实现
当需要从API获取搜索结果时:
<script>
export default {
methods: {
async searchAPI() {
const response = await fetch(`/api/items?q=${this.searchQuery}`)
this.items = await response.json()
}
},
watch: {
searchQuery(newVal) {
if (newVal.length > 2) {
this.searchAPI()
}
}
}
}
</script>
多条件搜索
实现多个字段的复合搜索:
<script>
export default {
computed: {
filteredItems() {
return this.items.filter(item => {
const query = this.searchQuery.toLowerCase()
return (
item.name.toLowerCase().includes(query) ||
item.description.toLowerCase().includes(query)
)
})
}
}
}
</script>
搜索提示与自动完成
添加搜索建议功能:
<template>
<input
v-model="searchQuery"
@input="getSuggestions"
@keydown.enter="performSearch"
/>
<ul v-if="suggestions.length">
<li
v-for="(suggestion, index) in suggestions"
:key="index"
@click="selectSuggestion(suggestion)"
>
{{ suggestion }}
</li>
</ul>
</template>
以上方法涵盖了Vue中实现搜索查询的常见场景,可根据实际需求选择适合的方案或组合使用。







