Storing Selected Products Locally
Use persistant storage APIs to save cart contents. Assign a unique identifier per user.
const userId = 'user_001';
const shoppingCart = [
{ productId: 101, productName: 'Product A', unitPrice: 25.99, count: 1 },
{ productId: 102, productName: 'Product B', unitPrice: 49.99, count: 2 }
];
wx.setStorageSync(userId, shoppingCart);
Displaying Cart Contents
Retrieve stored data and render in the cart interface.
const userId = 'user_001';
const storedCart = wx.getStorageSync(userId);
WXML rendering:
<scroll-view class="cart-container" scroll-y>
<view class="product-entry" wx:for="{{storedCart}}" wx:key="productId">
<text class="product-title">{{item.productName}}</text>
<text class="product-cost">${{item.unitPrice}}</text>
<text class="product-count">Qty: {{item.count}}</text>
</view>
</scroll-view>
Calculating Total Price and Quantity
Aggregate costs and item counts through iteration.
const userId = 'user_001';
const items = wx.getStorageSync(userId);
let sumCost = 0;
let totalItems = 0;
items.forEach(item => {
sumCost += item.unitPrice * item.count;
totalItems += item.count;
});
Handling Cart Operasions
Implement controls for quantity adjsutment and removal.
WXML controls:
<scroll-view class="cart-items" scroll-y>
<view class="item-card" wx:for="{{cartData}}" wx:key="productId" data-index="{{index}}">
<text>{{item.productName}}</text>
<text>${{item.unitPrice}}</text>
<view class="qty-control">
<button size="mini" bindtap="onDecrement">-</button>
<text>{{item.count}}</text>
<button size="mini" bindtap="onIncrement">+</button>
</view>
<button type="warn" size="mini" bindtap="onRemove">Remove</button>
</view>
</scroll-view>
Operation logic:
Page({
data: { cartData: [] },
onLoad() {
const userId = 'user_001';
this.setData({ cartData: wx.getStorageSync(userId) });
},
onDecrement(e) {
const idx = e.currentTarget.dataset.index;
let currentCart = this.data.cartData;
if (currentCart[idx].count > 1) {
currentCart[idx].count--;
this.updateCart(currentCart);
}
},
onIncrement(e) {
const idx = e.currentTarget.dataset.index;
let currentCart = this.data.cartData;
currentCart[idx].count++;
this.updateCart(currentCart);
},
onRemove(e) {
const idx = e.currentTarget.dataset.index;
let currentCart = this.data.cartData;
currentCart.splice(idx, 1);
this.updateCart(currentCart);
},
updateCart(updatedCart) {
const userId = 'user_001';
wx.setStorageSync(userId, updatedCart);
this.setData({ cartData: updatedCart });
}
});