vue搜索功能如何实现
实现Vue搜索功能的方法
使用计算属性过滤列表
在Vue中可以通过计算属性实现搜索功能。创建一个计算属性,根据搜索关键词过滤数组数据。
data() {
return {
searchQuery: '',
items: [
{ name: 'Apple' },
{ name: 'Banana' },
{ 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.name">
{{ item.name }}
</li>
</ul>
使用watch和debounce优化性能
对于大数据量或需要调用API的情况,可以使用watch配合debounce函数减少频繁触发。
data() {
return {
searchQuery: '',
searchResults: [],
timeout: null
}
},
watch: {
searchQuery(newVal) {
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.performSearch(newVal)
}, 300)
}
},
methods: {
performSearch(query) {
// 调用API或处理搜索逻辑
this.searchResults = this.items.filter(item =>
item.name.toLowerCase().includes(query.toLowerCase())
)
}
}
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以使用Fuse.js等模糊搜索库:
import Fuse from 'fuse.js'
data() {
return {
fuse: null,
searchQuery: '',
items: [...],
searchResults: []
}
},
created() {
this.fuse = new Fuse(this.items, {
keys: ['name', 'description'],
threshold: 0.4
})
},
watch: {
searchQuery(val) {
this.searchResults = val ? this.fuse.search(val) : this.items
}
}
服务端搜索实现
当数据量很大时,应该考虑服务端搜索:
methods: {
async searchItems() {
try {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.searchResults = response.data
} catch (error) {
console.error(error)
}
}
}
使用watch监听searchQuery变化并调用搜索方法:
watch: {
searchQuery: {
handler: 'searchItems',
immediate: true
}
}
添加搜索建议功能
实现自动完成或搜索建议功能:
data() {
return {
suggestions: [],
showSuggestions: false
}
},
methods: {
fetchSuggestions(query) {
if (query.length > 2) {
this.suggestions = this.items.filter(item =>
item.name.toLowerCase().startsWith(query.toLowerCase())
)
this.showSuggestions = true
}
},
selectSuggestion(item) {
this.searchQuery = item.name
this.showSuggestions = false
}
}
模板部分:
<input
v-model="searchQuery"
@input="fetchSuggestions(searchQuery)"
@focus="showSuggestions = true"
@blur="setTimeout(() => { showSuggestions = false }, 200)"
>
<ul v-if="showSuggestions && suggestions.length">
<li
v-for="item in suggestions"
:key="item.id"
@mousedown="selectSuggestion(item)"
>
{{ item.name }}
</li>
</ul>






