微信小程序实现购物车

164 阅读1分钟

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

  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 {
  padding10px;
}

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

.cart-item-img {
  width80px;
  height80px;
}

.cart-item-info {
  flex1;
  margin-left10px;
}

.cart-item-name {
  font-size16px;
  margin-bottom5px;
}

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

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

.cart-item-btn {
  width20px;
  height20px;
  background-color#eeeeee;
  border: none;
  outline: none;
  font-size14px;
  color#333333;
  text-align: center;
  line-height20px;
  cursor: pointer;
}

.cart-item-quantity-text {
  margin0 10px;
}
  1. 在购物车页面的 js 文件(cart.js)中编写逻辑代码:
Page({
  data: {
    cartList: [] // 购物车列表数据
  },
  onLoadfunction () {
    this.getCartList(); // 页面加载时调用接口获取购物车列表数据
  },
  getCartListfunction () {
    // 调用接口获取购物车列表数据
    wx.request({
      url'接口地址',
      success(res) => {
        this.setData({
          cartList: res.data
        });
      },
      fail(err) => {
        console.error(err);
      }
    });
  },
  reduceQuantityfunction (e) {
    const index = e.currentTarget.dataset.index;
    const cartList = this.data.cartList;
    if (cartList[index].quantity > 1) {
      cartList[index].quantity--;
      this.setData({
        cartList: cartList
      });
    }
  },
  addQuantityfunction (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": "购物车"
}