vue实现简单搜索
实现简单搜索功能
在Vue中实现搜索功能可以通过多种方式完成,以下是几种常见的方法:
使用v-model和computed属性
创建一个输入框绑定到数据属性,使用computed属性过滤结果:
<template>
<div>
<input v-model="searchQuery" placeholder="Search...">
<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>
使用watch实现搜索
当需要更复杂的搜索逻辑或异步操作时,可以使用watch:
<script>
export default {
data() {
return {
searchQuery: '',
items: [],
allItems: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' }
]
}
},
watch: {
searchQuery(newVal) {
this.items = this.allItems.filter(item =>
item.name.toLowerCase().includes(newVal.toLowerCase())
)
}
},
created() {
this.items = [...this.allItems]
}
}
</script>
使用第三方库实现高级搜索
对于更复杂的搜索需求,可以使用如Fuse.js等库:
import Fuse from 'fuse.js'
// 在组件中
methods: {
setupFuse() {
const options = {
keys: ['name', 'description'],
threshold: 0.4
}
this.fuse = new Fuse(this.allItems, options)
},
search() {
this.items = this.searchQuery ?
this.fuse.search(this.searchQuery).map(r => r.item) :
[...this.allItems]
}
},
created() {
this.setupFuse()
this.search()
}
使用Vuex管理搜索状态
在大型应用中,可以使用Vuex集中管理搜索状态:
// store.js
export default new Vuex.Store({
state: {
searchQuery: '',
items: [...]
},
getters: {
filteredItems: state => {
return state.items.filter(item =>
item.name.toLowerCase().includes(state.searchQuery.toLowerCase())
)
}
}
})
// 组件中
computed: {
...mapGetters(['filteredItems']),
searchQuery: {
get() { return this.$store.state.searchQuery },
set(value) { this.$store.commit('updateSearchQuery', value) }
}
}
实现搜索防抖
为防止频繁触发搜索,可以添加防抖功能:
import { debounce } from 'lodash'
methods: {
search: debounce(function() {
// 搜索逻辑
}, 300)
}
以上方法可以根据项目需求选择使用,从简单到复杂提供了不同层次的实现方案。







