微信小程序实现购物车功能

要实现购物车功能并调用接口,首先需要在微信小程序中创建一个购物车页面,然后在该页面中编写相关代码。

  1. 创建购物车页面 wxml 文件(cart.wxml):
<view class="cart-list">
  <block wx:for="{{cartList}}" wx:key="index">
    <view class="cart-item">
      <image src="{{item.image}}" class="cart-item-img"></image>
      <view class="cart-item-info">
        <view class="cart-item-name">{{item.name}}</view>
        <view class="cart-item-price">¥{{item.price}}</view>
      </view>
      <view class="cart-item-quantity">
        <button class="cart-item-btn" bindtap="reduceQuantity">-</button>
        <view class="cart-item-quantity-text">{{item.quantity}}</view>
        <button class="cart-item-btn" bindtap="addQuantity">+</button>
      </view>
    </view>
  </block>
</view>
  1. 创建购物车页面的样式文件(cart.wxss):
.cart-list {
  padding: 10px;
}

.cart-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.cart-item-img {
  width: 80px;
  height: 80px;
}

.cart-item-info {
  flex: 1;
  margin-left: 10px;
}

.cart-item-name {
  font-size: 16px;
  margin-bottom: 5px;
}

.cart-item-price {
  color: #999999;
}

.cart-item-quantity {
  display: flex;
  align-items: center;
}

.cart-item-btn {
  width: 20px;
  height: 20px;
  background-color: #eeeeee;
  border: none;
  outline: none;
  font-size: 14px;
  color: #333333;
  text-align: center;
  line-height: 20px;
  cursor: pointer;
}

.cart-item-quantity-text {
  margin: 0 10px;
}
  1. 在购物车页面的 js 文件(cart.js)中编写逻辑代码:
Page({
  data: {
    cartList: [] // 购物车列表数据
  },
  onLoad: function () {
    this.getCartList(); // 页面加载时调用接口获取购物车列表数据
  },
  getCartList: function () {
    // 调用接口获取购物车列表数据
    wx.request({
      url: '接口地址',
      success: (res) => {
        this.setData({
          cartList: res.data
        });
      },
      fail: (err) => {
        console.error(err);
      }
    });
  },
  reduceQuantity: function (e) {
    const index = e.currentTarget.dataset.index;
    const cartList = this.data.cartList;
    if (cartList[index].quantity > 1) {
      cartList[index].quantity--;
      this.setData({
        cartList: cartList
      });
    }
  },
  addQuantity: function (e) {
    const index = e.currentTarget.dataset.index;
    const cartList = this.data.cartList;
    cartList[index].quantity++;
    this.setData({
      cartList: cartList
    });
  }
});

getCartList 函数用于调用接口获取购物车列表数据,并将数据保存在 cartList 变量中;reduceQuantityaddQuantity 函数分别用于减少和增加商品数量,并更新购物车列表数据。

最后,在购物车页面的 json 文件(cart.json)中添加页面配置:

{
  "navigationBarTitleText": "购物车"
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容