uniapp 过滤组件的使用方法 uniapp如何实现过滤组件功能
在uniapp中如何实现过滤组件的功能?比如想要做一个商品列表的筛选功能,可以通过下拉选择或者多选条件来过滤显示不同的商品。请问有没有具体的代码示例或者组件推荐?最好能支持动态更新过滤条件和实时显示结果。
2 回复
在uni-app中,可通过以下方式实现过滤组件:
- 使用计算属性computed进行数据过滤
computed: {
filteredList() {
return this.list.filter(item => item.status === 'active')
}
}
- 使用过滤器filter(Vue 2.x)
filters: {
formatDate(value) {
// 过滤逻辑
}
}
-
自定义组件封装过滤逻辑 创建独立组件处理特定过滤需求
-
使用第三方工具库如lodash的filter方法
推荐使用计算属性,性能更好且响应式。
在 UniApp 中,过滤组件通常用于筛选或处理数据,例如搜索、分类或格式化显示。以下是实现过滤组件功能的常用方法:
1. 使用计算属性(推荐)
在 Vue 组件中,通过 computed 属性对数据进行实时过滤,无需手动触发。
export default {
data() {
return {
list: [
{ name: '苹果', category: '水果' },
{ name: '香蕉', category: '水果' },
{ name: '胡萝卜', category: '蔬菜' }
],
filterText: ''
};
},
computed: {
filteredList() {
return this.list.filter(item =>
item.name.includes(this.filterText)
);
}
}
};
在模板中直接使用 filteredList:
<input v-model="filterText" placeholder="输入关键词过滤" />
<view v-for="item in filteredList" :key="item.name">
{{ item.name }} - {{ item.category }}
</view>
2. 使用方法过滤
通过方法手动触发过滤,适用于复杂逻辑或需要外部触发的场景。
export default {
data() {
return {
list: [...], // 同上
filterText: '',
result: []
};
},
methods: {
filterData() {
this.result = this.list.filter(item =>
item.name.includes(this.filterText)
);
}
},
onLoad() {
this.filterData(); // 初始加载数据
}
};
模板中绑定事件:
<input v-model="filterText" [@input](/user/input)="filterData" />
<view v-for="item in result" :key="item.name">
{{ item.name }}
</view>
3. 结合下拉选择器过滤
添加分类选择功能,实现多条件过滤:
export default {
data() {
return {
list: [...], // 同上
selectedCategory: '',
filterText: ''
};
},
computed: {
filteredList() {
return this.list.filter(item => {
const matchText = item.name.includes(this.filterText);
const matchCategory = !this.selectedCategory || item.category === this.selectedCategory;
return matchText && matchCategory;
});
}
}
};
模板示例:
<input v-model="filterText" placeholder="搜索名称" />
<picker [@change](/user/change)="onCategoryChange" :value="selectedCategory" :range="['水果', '蔬菜']">
<view>当前分类:{{ selectedCategory || '全部' }}</view>
</picker>
<view v-for="item in filteredList" :key="item.name">
{{ item.name }}
</view>
4. 使用过滤器(Vue 过滤器)
适用于简单文本格式化,但 UniApp 中 Vue 3 已移除过滤器,建议用计算属性或方法替代。
注意事项:
- 性能优化:大数据量时,使用计算属性可能频繁触发,可结合防抖(如
lodash.debounce)减少计算次数。 - 复杂过滤:多条件筛选时,确保逻辑清晰,避免嵌套过深。
以上方法覆盖了常见过滤需求,根据实际场景选择即可。

