微信小程序写一个商品展示页面,包括商品分类、各类商品展示并可加入购物车
时间: 2024-05-02 11:16:13 浏览: 19
好的,以下是一个简单的微信小程序商品展示页面的代码示例:
1. 首先需要在 app.json 中配置页面路径:
```
"pages": [
"pages/index/index",
"pages/goods/goods"
]
```
2. 在 index 页面中添加商品分类和商品展示的代码:
```
<view class="category">
<view class="item {{activeIndex === index ? 'active' : ''}}" bindtap="switchTab" data-index="{{index}}" wx:for="{{categories}}" wx:key="index">{{item}}</view>
</view>
<view class="goods">
<view class="item" wx:for="{{goodsList}}" wx:key="index">
<image class="image" src="{{item.image}}" mode="aspectFill"></image>
<view class="info">
<view class="name">{{item.name}}</view>
<view class="price">¥{{item.price}}</view>
<button class="add-to-cart" bindtap="addToCart" data-index="{{index}}">加入购物车</button>
</view>
</view>
</view>
```
3. 在 js 文件中添加分类和商品数据以及相关方法:
```
Page({
data: {
categories: ['全部', '食品', '饮料', '日用品'],
activeIndex: 0,
goodsList: [
{
name: '可口可乐',
price: '3.00',
image: '/images/cocacola.png',
category: '饮料'
},
{
name: '洁柔纸巾',
price: '2.50',
image: '/images/jierou.png',
category: '日用品'
},
// 其他商品...
],
cartList: []
},
switchTab: function(e) {
const index = e.currentTarget.dataset.index;
this.setData({
activeIndex: index
});
},
addToCart: function(e) {
const index = e.currentTarget.dataset.index;
const item = this.data.goodsList[index];
const cartList = this.data.cartList;
const i = cartList.findIndex(x => x.name === item.name);
if (i > -1) {
cartList[i].count++;
} else {
cartList.push({
name: item.name,
price: item.price,
image: item.image,
count: 1
});
}
wx.showToast({
title: '已加入购物车',
icon: 'success'
});
this.setData({
cartList: cartList
});
}
});
```
4. 在购物车页面中展示已选商品和总价:
```
<view class="cart">
<view class="item" wx:for="{{cartList}}" wx:key="name">
<image class="image" src="{{item.image}}" mode="aspectFill"></image>
<view class="info">
<view class="name">{{item.name}}</view>
<view class="price">¥{{item.price}} × {{item.count}}</view>
</view>
</view>
<view class="total-price">总价:¥{{totalPrice}}</view>
</view>
```
5. 在 js 文件中计算总价:
```
Page({
data: {
cartList: []
},
get totalPrice() {
return this.data.cartList.reduce((acc, cur) => acc + cur.price * cur.count, 0).toFixed(2);
}
});
```
以上是一个简单的微信小程序商品展示页面的代码示例,可以根据需求进行修改和完善。