vue实现搜索框检索
实现基础搜索框
在Vue中创建一个基础搜索框,使用v-model双向绑定输入值,通过计算属性或方法过滤数据:
<template>
<div>
<input v-model="searchQuery" placeholder="搜索..." />
<ul>
<li v-for="item in filteredList" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
},
computed: {
filteredList() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
添加防抖优化
为防止频繁触发搜索,可使用lodash的debounce方法或自定义防抖函数:
import { debounce } from 'lodash'
export default {
methods: {
search: debounce(function() {
// 实际搜索逻辑
this.filteredList = this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}, 300)
}
}
远程数据搜索
当需要从API获取搜索结果时,可使用axios等HTTP库:
export default {
methods: {
async searchRemote() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.results = response.data
} catch (error) {
console.error(error)
}
}
}
}
添加搜索建议
实现自动完成功能,在用户输入时显示搜索建议:
<template>
<div>
<input
v-model="searchQuery"
@input="showSuggestions"
@focus="showSuggestions"
@blur="hideSuggestions"
/>
<ul v-if="showSuggestionList">
<li
v-for="suggestion in suggestions"
:key="suggestion.id"
@click="selectSuggestion(suggestion)"
>
{{ suggestion.text }}
</li>
</ul>
</div>
</template>
高亮匹配结果
在搜索结果中高亮显示匹配的文本部分:
highlightText(text) {
if (!this.searchQuery) return text
const regex = new RegExp(this.searchQuery, 'gi')
return text.replace(regex, match => `<span class="highlight">${match}</span>`)
}
多条件搜索
实现基于多个字段的复合搜索:
filteredList() {
return this.items.filter(item => {
const query = this.searchQuery.toLowerCase()
return (
item.name.toLowerCase().includes(query) ||
item.description.toLowerCase().includes(query) ||
item.category.toLowerCase().includes(query)
)
})
}
路由集成
将搜索参数同步到URL路由中,支持浏览器前进后退:
watch: {
searchQuery(newVal) {
this.$router.push({ query: { q: newVal } })
}
},
created() {
if (this.$route.query.q) {
this.searchQuery = this.$route.query.q
}
}






