在微信小程序中实现一个左侧为商品类型选择,右侧显示商品列表的效果,通常涉及到使用
scroll-view
、view
、swiper
等组件来布局和展示内容。下面是一个简单的实现思路和代码示例:
设计布局
我们可以使用一个 scroll-view
包裹左侧的商品类型列表,右侧用一个 scroll-view
或 view
来展示商品列表。为了实现联动效果,可以在点击商品类型时更新右侧的商品列表。
基本结构
<view class="container">
<!-- 左侧商品类型选择 -->
<scroll-view class="left-side" scroll-y="true" scroll-with-animation>
<view class="item" wx:for="{
{categories}}" wx:key="index" bindtap="onCategoryChange" data-category="{
{item}}">
{
{item.name}}
</view>
</scroll-view>
<!-- 右侧商品列表 -->
<scroll-view class="right-side" scroll-y="true" scroll-with-animation>
<view class="product" wx:for="{
{products}}" wx:key="index">
<image src="{
{item.image}}" class="product-image" />
<view class="product-info">
<text>{
{item.name}}</text>
<text>{
{item.price}}</text>
</view>
</view>
</scroll-view>
</view>
页面样式
.container {
display: flex;
}
.left-side {
width: 200rpx;
height: 100%;
background-color: #f5f5f5;
}
.right-side {
flex: 1;
padding: 20rpx;
}
.item {
padding: 10rpx;
text-align: center;
background-color: #ffffff;
margin-bottom: 10rpx;
border-radius: 5rpx;
}
.product {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 20rpx;
}
.product-image {
width: 150rpx;
height: 150rpx;
}
.product-info {
text-align: center;
}
页面逻辑
在 js
文件中,处理商品类型的点击事件,并根据选中的类型更新商品列表:
Page({
data: {
categories: [
{
id: 1, name: '电子产品' },
{
id: 2, name: '服装' },
{
id: 3, name: '家居' },
// 其他类别...
],
products: [], // 商品列表
},
onLoad: function () {
// 初始加载电子产品的商品列表
this.loadProductsByCategory(1);
},
// 处理点击类别,更新商品列表
onCategoryChange: function (e) {
const category = e.currentTarget.dataset.category;
this.loadProductsByCategory(category.id);
},
// 根据类别加载商品
loadProductsByCategory: function (categoryId) {
// 假设这里是从服务器获取数据,示例使用静态数据
let productList = [