微信小程序列表渲染筛选
时间: 2023-07-06 11:27:49 浏览: 92
微信小程序中可以使用 `wx:for` 标签来进行列表渲染,同时也可以通过自定义属性来实现筛选功能。以下是一个简单的示例:
```html
<view>
<picker mode="selector" range="{{categories}}" bindchange="onCategoryChange">
<view class="picker">
{{category}}
<image src="/images/arrow-down.png"></image>
</view>
</picker>
<scroll-view scroll-y="true" style="height: 500rpx;">
<view wx:for="{{filteredItems}}" wx:key="id">
<view>{{item.name}}</view>
<view>{{item.category}}</view>
</view>
</scroll-view>
</view>
```
在上面的代码中,我们使用了 `<picker>` 标签来展示一个下拉列表,用户可以选择不同的分类。当用户选择某个分类后,我们会触发 `onCategoryChange` 函数来更新 `category` 变量的值,并重新计算 `filteredItems` 数组,以过滤出符合当前分类的数据项。
以下是相应的 JavaScript 代码:
```javascript
Page({
data: {
items: [
{ id: 1, name: 'Item 1', category: 'Category A' },
{ id: 2, name: 'Item 2', category: 'Category B' },
{ id: 3, name: 'Item 3', category: 'Category A' },
{ id: 4, name: 'Item 4', category: 'Category C' },
{ id: 5, name: 'Item 5', category: 'Category B' },
],
categories: ['All', 'Category A', 'Category B', 'Category C'],
category: 'All',
filteredItems: [],
},
onCategoryChange: function(e) {
const index = e.detail.value;
const category = this.data.categories[index];
const items = this.data.items;
let filteredItems = items;
if (category !== 'All') {
filteredItems = items.filter(item => item.category === category);
}
this.setData({
category: category,
filteredItems: filteredItems,
});
}
});
```
在上面的代码中,我们定义了一个 `items` 数组来存储所有数据项,一个 `categories` 数组来存储所有分类,一个 `category` 变量来存储当前选择的分类,以及一个 `filteredItems` 数组来存储当前分类下的所有数据项。当用户选择某个分类后,我们会根据该分类过滤出符合条件的数据项,并更新 `filteredItems` 数组,以触发列表渲染。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)