vue搜索怎么实现
Vue搜索功能实现方法
在Vue中实现搜索功能通常需要结合数据绑定、计算属性和方法。以下是几种常见的实现方式:
使用计算属性过滤数据
<template>
<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</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>
使用watch监听搜索词变化
<script>
export default {
data() {
return {
searchQuery: '',
items: [...],
filteredItems: []
}
},
watch: {
searchQuery(newVal) {
this.filteredItems = this.items.filter(item =>
item.name.toLowerCase().includes(newVal.toLowerCase())
)
}
}
}
</script>
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以考虑使用第三方库如Fuse.js:
import Fuse from 'fuse.js'
// 在组件中
methods: {
setupFuse() {
const options = {
keys: ['name', 'description'],
threshold: 0.4
}
this.fuse = new Fuse(this.items, options)
},
search() {
this.filteredItems = this.searchQuery
? this.fuse.search(this.searchQuery).map(r => r.item)
: this.items
}
}
实现防抖优化性能
对于频繁触发的搜索,可以使用防抖技术:
import { debounce } from 'lodash'
// 在组件中
methods: {
search: debounce(function() {
// 搜索逻辑
}, 300)
}
服务端搜索实现
当数据量较大时,可以考虑服务端搜索:
methods: {
async search() {
try {
const response = await axios.get('/api/search', {
params: { q: this.searchQuery }
})
this.results = response.data
} catch (error) {
console.error(error)
}
}
}
以上方法可以根据具体需求选择或组合使用,计算属性方式适合客户端小型数据集搜索,而服务端搜索适合大数据量场景。







