vue 搜索功能实现
实现 Vue 搜索功能的方法
基于计算属性的前端搜索
使用 Vue 的计算属性实现客户端搜索,适合数据量较小的场景。通过 v-model 绑定搜索输入框,计算属性过滤列表数据。
<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: '香蕉' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用 Lodash 的防抖优化
对于频繁触发的搜索输入,使用 Lodash 的 debounce 函数减少计算次数。

import { debounce } from 'lodash'
export default {
methods: {
handleSearch: debounce(function(query) {
// 执行搜索逻辑
}, 300)
}
}
结合后端 API 搜索
当数据量较大时,通过 API 请求后端搜索接口,通常需要处理异步操作和加载状态。

export default {
data() {
return {
searchResults: [],
isLoading: false
}
},
methods: {
async searchItems(query) {
this.isLoading = true
try {
const response = await axios.get('/api/search', { params: { q: query } })
this.searchResults = response.data
} finally {
this.isLoading = false
}
}
}
}
使用 Vuex 管理搜索状态
在大型应用中,使用 Vuex 集中管理搜索状态和逻辑。
// store/modules/search.js
export default {
state: {
results: [],
query: ''
},
mutations: {
SET_RESULTS(state, results) {
state.results = results
},
SET_QUERY(state, query) {
state.query = query
}
},
actions: {
async search({ commit }, query) {
const response = await axios.get('/api/search', { params: { q: query } })
commit('SET_RESULTS', response.data)
}
}
}
实现高级搜索功能
对于需要多条件搜索的场景,可以构建更复杂的搜索参数对象。
data() {
return {
searchParams: {
keyword: '',
category: '',
priceRange: [0, 100]
}
}
},
methods: {
async advancedSearch() {
const params = {
q: this.searchParams.keyword,
category: this.searchParams.category,
min_price: this.searchParams.priceRange[0],
max_price: this.searchParams.priceRange[1]
}
const response = await axios.get('/api/search', { params })
this.results = response.data
}
}
注意事项
- 对于中文搜索,确保比较前统一转换为相同大小写
- 考虑使用 Web Worker 处理大量数据的本地搜索
- 移动端注意虚拟键盘的显示/隐藏事件处理
- 搜索结果为空时显示友好提示
- 分页加载大数据集时实现无限滚动或分页控件






