vue如何实现搜索过滤
Vue 实现搜索过滤的方法
使用计算属性过滤数据
计算属性可以根据搜索关键词动态过滤数组数据,适合处理本地数据。
<template>
<input v-model="searchQuery" placeholder="搜索...">
<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: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
使用 watch 监听搜索变化
当需要执行异步操作或复杂逻辑时,可以使用 watch 监听搜索词变化。
<script>
export default {
data() {
return {
searchQuery: '',
filteredItems: [],
allItems: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
}
},
watch: {
searchQuery(newVal) {
this.filteredItems = this.allItems.filter(item =>
item.name.toLowerCase().includes(newVal.toLowerCase())
)
}
},
created() {
this.filteredItems = [...this.allItems]
}
}
</script>
结合 Vuex 实现全局搜索
在大型应用中,可以使用 Vuex 管理搜索状态和过滤逻辑。

// store.js
const store = new Vuex.Store({
state: {
searchQuery: '',
items: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' }
]
},
getters: {
filteredItems: state => {
return state.items.filter(item =>
item.name.toLowerCase().includes(state.searchQuery.toLowerCase())
)
}
},
mutations: {
updateSearchQuery(state, query) {
state.searchQuery = query
}
}
})
使用第三方库实现高级搜索
对于复杂搜索需求,可以集成如 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.filteredItems = this.searchQuery
? this.fuse.search(this.searchQuery).map(r => r.item)
: [...this.allItems]
}
},
created() {
this.setupFuse()
}
服务端搜索实现
当数据量很大时,应该将搜索逻辑放在服务端。

methods: {
async searchItems() {
try {
const response = await axios.get('/api/items', {
params: { q: this.searchQuery }
})
this.filteredItems = response.data
} catch (error) {
console.error(error)
}
}
},
watch: {
searchQuery() {
this.searchItems()
}
}
性能优化技巧
添加防抖函数避免频繁触发搜索,适合处理实时搜索场景。
import { debounce } from 'lodash'
methods: {
search: debounce(function() {
// 搜索逻辑
}, 300)
}
使用虚拟滚动处理大量搜索结果,提升渲染性能。
<template>
<RecycleScroller
:items="filteredItems"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div>{{ item.name }}</div>
</RecycleScroller>
</template>
多条件筛选实现
扩展搜索功能支持多个筛选条件。
computed: {
filteredItems() {
return this.items.filter(item => {
const matchesSearch = item.name.toLowerCase().includes(
this.searchQuery.toLowerCase()
)
const matchesCategory = this.selectedCategory
? item.category === this.selectedCategory
: true
return matchesSearch && matchesCategory
})
}
}






