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: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用 Lodash 防抖优化性能
频繁触发搜索可能导致性能问题,可以使用 Lodash 的 debounce 方法优化。

<template>
<input v-model="searchQuery" @input="debouncedSearch">
</template>
<script>
import _ from 'lodash'
export default {
data() {
return {
searchQuery: '',
items: []
}
},
created() {
this.debouncedSearch = _.debounce(this.doSearch, 500)
},
methods: {
doSearch() {
// 执行搜索逻辑或API调用
}
}
}
</script>
结合 API 请求实现远程搜索
对于大量数据,通常需要调用后端 API 实现搜索。

<template>
<input v-model="searchQuery" @input="handleSearch">
</template>
<script>
export default {
data() {
return {
searchQuery: '',
results: []
}
},
methods: {
async handleSearch() {
if (this.searchQuery.length < 2) return
const response = await fetch(`/api/search?q=${this.searchQuery}`)
this.results = await response.json()
}
}
}
</script>
使用 Vuex 管理搜索状态
在大型应用中,可以使用 Vuex 集中管理搜索状态。
// store.js
export default new Vuex.Store({
state: {
searchQuery: '',
searchResults: []
},
mutations: {
SET_SEARCH_QUERY(state, query) {
state.searchQuery = query
},
SET_SEARCH_RESULTS(state, results) {
state.searchResults = results
}
},
actions: {
async search({ commit }, query) {
commit('SET_SEARCH_QUERY', query)
const results = await api.search(query)
commit('SET_SEARCH_RESULTS', results)
}
}
})
添加搜索建议功能
实现搜索建议可以提升用户体验。
<template>
<div>
<input
v-model="searchQuery"
@input="fetchSuggestions"
@focus="showSuggestions = true"
@blur="hideSuggestions"
>
<ul v-show="showSuggestions && suggestions.length">
<li
v-for="suggestion in suggestions"
:key="suggestion"
@mousedown="selectSuggestion(suggestion)"
>
{{ suggestion }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
suggestions: [],
showSuggestions: false
}
},
methods: {
async fetchSuggestions() {
if (this.searchQuery.length > 1) {
this.suggestions = await api.getSuggestions(this.searchQuery)
}
},
selectSuggestion(suggestion) {
this.searchQuery = suggestion
this.showSuggestions = false
},
hideSuggestions() {
setTimeout(() => {
this.showSuggestions = false
}, 200)
}
}
}
</script>
这些方法涵盖了 Vue 中实现搜索功能的不同场景和优化方案,可以根据具体需求选择适合的实现方式。






