vue实现总览和筛选
Vue 实现总览和筛选功能
在 Vue 中实现总览和筛选功能,通常需要结合数据绑定、计算属性和事件处理。以下是一个完整的实现方案。
数据准备
在 Vue 的 data 中定义初始数据和筛选条件:
data() {
return {
items: [
{ id: 1, name: 'Item 1', category: 'A' },
{ id: 2, name: 'Item 2', category: 'B' },
{ id: 3, name: 'Item 3', category: 'A' }
],
filterCategory: ''
}
}
计算属性实现筛选
使用计算属性动态返回筛选后的数据:

computed: {
filteredItems() {
if (!this.filterCategory) return this.items
return this.items.filter(item =>
item.category === this.filterCategory
)
}
}
模板渲染
在模板中同时显示总览和筛选结果:
<div>
<h3>总览</h3>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }} ({{ item.category }})
</li>
</ul>
<h3>筛选</h3>
<select v-model="filterCategory">
<option value="">All</option>
<option value="A">Category A</option>
<option value="B">Category B</option>
</select>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }} ({{ item.category }})
</li>
</ul>
</div>
多条件筛选扩展
对于更复杂的筛选需求,可以扩展筛选逻辑:

data() {
return {
filters: {
category: '',
searchQuery: ''
}
}
},
computed: {
filteredItems() {
return this.items.filter(item => {
const matchesCategory = !this.filters.category ||
item.category === this.filters.category
const matchesSearch = !this.filters.searchQuery ||
item.name.toLowerCase().includes(this.filters.searchQuery.toLowerCase())
return matchesCategory && matchesSearch
})
}
}
性能优化
对于大型数据集,可以考虑以下优化:
- 使用 debounce 处理搜索输入
- 添加分页功能
- 使用虚拟滚动渲染长列表
组件化实现
将筛选逻辑封装为可复用组件:
<template>
<div>
<filter-controls @filter="applyFilters" />
<item-list :items="filteredItems" />
</div>
</template>
<script>
export default {
components: {
FilterControls,
ItemList
},
methods: {
applyFilters(filters) {
this.activeFilters = filters
}
}
}
</script>
这种方法提供了清晰的关注点分离,使总览和筛选功能更易于维护和扩展。






