vue搜索功能实现
实现Vue搜索功能的方法
基础搜索实现
在Vue组件中声明一个搜索词数据属性和一个列表数据属性
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())
)
}
}
在模板中使用v-model绑定搜索输入框
<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
高级搜索功能
实现多字段搜索

computed: {
filteredItems() {
const query = this.searchQuery.toLowerCase()
return this.items.filter(item =>
item.name.toLowerCase().includes(query) ||
item.description.toLowerCase().includes(query)
)
}
}
添加搜索延迟(防抖)
import _ from 'lodash'
methods: {
search: _.debounce(function(query) {
this.searchQuery = query
}, 500)
}
服务器端搜索
使用axios发送搜索请求

methods: {
async searchItems() {
try {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.items = response.data
} catch (error) {
console.error(error)
}
}
}
添加搜索按钮触发
<input v-model="searchQuery" @keyup.enter="searchItems">
<button @click="searchItems">Search</button>
搜索建议实现
添加搜索建议功能
data() {
return {
suggestions: [],
showSuggestions: false
}
},
methods: {
async getSuggestions() {
if(this.searchQuery.length > 2) {
const response = await axios.get('/api/suggestions', {
params: { q: this.searchQuery }
})
this.suggestions = response.data
this.showSuggestions = true
}
}
}
在模板中显示建议
<ul v-if="showSuggestions && suggestions.length">
<li
v-for="suggestion in suggestions"
:key="suggestion.id"
@click="selectSuggestion(suggestion)"
>
{{ suggestion.name }}
</li>
</ul>






