vue 实现筛选
实现筛选功能的基本方法
在Vue中实现筛选功能通常涉及以下几个核心步骤:
数据绑定与筛选逻辑
使用v-model绑定筛选条件到Vue实例的数据属性,结合计算属性实现动态筛选:
data() {
return {
searchQuery: '',
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' }
]
}
},
computed: {
filteredItems() {
return this.items.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
模板中的筛选展示
在模板中使用计算属性展示筛选结果:
<input v-model="searchQuery" placeholder="Search...">
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
多条件筛选实现
对于更复杂的多条件筛选,可以扩展筛选逻辑:
组合筛选条件
data() {
return {
filters: {
name: '',
category: '',
priceRange: [0, 100]
},
products: [...]
}
},
computed: {
filteredProducts() {
return this.products.filter(product => {
const nameMatch = product.name.includes(this.filters.name)
const categoryMatch = product.category === this.filters.category
const priceMatch = product.price >= this.filters.priceRange[0] &&
product.price <= this.filters.priceRange[1]
return nameMatch && categoryMatch && priceMatch
})
}
}
动态筛选表单
<input v-model="filters.name" placeholder="Product name">
<select v-model="filters.category">
<option value="">All Categories</option>
<option v-for="cat in categories" :value="cat">{{ cat }}</option>
</select>
性能优化技巧
对于大型数据集,可以采用以下优化方法:
防抖处理
使用lodash的debounce方法减少频繁筛选导致的性能问题:
import { debounce } from 'lodash'
methods: {
handleSearch: debounce(function() {
this.filteredItems = this.applyFilters()
}, 300)
}
分页加载
结合分页组件减少一次性渲染的数据量:
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.pageSize
return this.filteredItems.slice(start, start + this.pageSize)
}
}
高级筛选模式
自定义筛选函数
允许传入自定义筛选函数增加灵活性:
props: {
filterFn: {
type: Function,
default: (item, query) => item.includes(query)
}
},
computed: {
filteredData() {
return this.data.filter(item => this.filterFn(item, this.query))
}
}
服务端筛选
对于大数据量,考虑实现服务端筛选:
methods: {
async fetchFilteredData() {
const response = await axios.get('/api/items', {
params: {
search: this.searchQuery,
page: this.currentPage
}
})
this.items = response.data
}
}
以上方法可根据具体需求组合使用,构建出适合不同场景的筛选功能。关键点在于合理利用Vue的响应式系统和计算属性来实现高效的数据筛选。







