在小程序中实现多条件筛选页面,通常需要结合前端的筛选逻辑和后端的接口支持。以下是一个简单的示例,展示如何在小程序中实现多条件筛选页面。
1. 后端接口
假设我们的后端接口是 `/api/search?filters=...`,其中 `filters` 是一个 JSON 字符串,表示筛选条件。例如:
data.json
{ "category": "电子产品", "brand": "Apple", "priceRange": [100, 500] }
2. 小程序代码
2.1 页面结构
首先,我们定义页面结构,包括筛选条件的输入框和按钮。
<!-- pages/search/search.wxml --> <view class="container"> <view class="filter-section"> <view class="filter-item"> <text>类别:</text> <picker bindchange="categoryChange" range="{{categories}}" value="{{selectedCategory}}"> <view class="picker">{{selectedCategoryName}}</view> </picker> </view> <view class="filter-item"> <text>品牌:</text> <picker bindchange="brandChange" range="{{brands}}" value="{{selectedBrand}}"> <view class="picker">{{selectedBrandName}}</view> </picker> </view> <view class="filter-item"> <text>价格范围:</text> <input type="number" placeholder="最低价" bindinput="minPriceChange" value="{{minPrice}}"/> <text>-</text> <input type="number" placeholder="最高价" bindinput="maxPriceChange" value="{{maxPrice}}"/> </view> <button bindtap="search">搜索</button> </view> <view class="results"> <block wx:for="{{results}}" wx:key="id"> <view class="result-item">{{item.name}}</view> </block> </view> </view>
2.2 页面逻辑
接下来,我们定义页面逻辑,包括处理筛选条件的变化和发起搜索请求。
// pages/search/search.js
Page({ data: { categories: ['电子产品', '家居用品', '服装鞋包'], // 类别列表 brands: ['Apple', 'Samsung', 'Xiaomi'], // 品牌列表 selectedCategory: 0, // 当前选中的类别索引 selectedBrand: 0, // 当前选中的品牌索引 minPrice: '', // 最低价 maxPrice: '', // 最高价 results: [], // 搜索结果 }, // 类别变化事件 categoryChange(e) { this.setData({ selectedCategory: e.detail.value }); }, // 品牌变化事件 brandChange(e) { this.setData({ selectedBrand: e.detail.value }); }, // 最低价变化事件 minPriceChange(e) { this.setData({ minPrice: e.detail.value }); }, // 最高价变化事件 maxPriceChange(e) { this.setData({ maxPrice: e.detail.value }); }, // 搜索按钮点击事件 search() { const filters = { category: this.data.categories[this.data.selectedCategory], brand: this.data.brands[this.data.selectedBrand], priceRange: [this.data.minPrice, this.data.maxPrice], }; this.getResults(filters); }, // 获取搜索结果 getResults(filters) { const url = `/api/search?filters=${encodeURIComponent(JSON.stringify(filters))}`; wx.request({ url, method: 'GET', success: (res) => { this.setData({ results: res.data }); }, fail: (err) => { console.error('请求失败', err); }, }); }, });