写一个微信小程序代码,仿照淘宝APP
时间: 2023-03-13 21:52:11 浏览: 136
var app = getApp();
Page({
data: {
// 页面状态
pageStatus: 'loading',
// 购物车数据
cart: [],
// 初始总价
totalPrice: 0,
// 全选状态
selectAllStatus: false,
},
onLoad: function () {
this.setData({
pageStatus: 'success',
cart: [{
id: 1,
title: '商品标题',
image: 'http://www.example.com/image.jpg',
num: 1,
price: 199,
selected: false
}]
});
},
// 选择
selectList(e) {
const index = e.currentTarget.dataset.index;
let cart = this.data.cart;
const selected = cart[index].selected;
cart[index].selected = !selected;
this.setData({
cart: cart
});
this.getTotalPrice();
},
// 全选
selectAll(e) {
let selectAllStatus = this.data.selectAllStatus;
selectAllStatus = !selectAllStatus;
let cart = this.data.cart; for (let i = 0; i < cart.length; i++) {
cart[i].selected = selectAllStatus;
}
this.setData({
selectAllStatus: selectAllStatus,
cart: cart
});
this.getTotalPrice();
},
// 数量减
numDesc(e) {
const index = e.currentTarget.dataset.index;
let cart = this.data.cart;
let num = cart[index].num;
if (num <= 1) {
return false;
}
num = num - 1;
cart[index].num = num;
this.setData({
cart: cart
});
this.getTotalPrice();
},
// 数量加
numAsc(e) {
const index = e.currentTarget.dataset.index;
let cart = this.data.cart;
let num = cart[index].num;
num = num + 1;
cart[index].num = num;
this.setData({
cart: cart
});
this.getTotalPrice();
},
// 计算总价
getTotalPrice() {
let cart = this.data.cart;
let total = 0;
for (let i = 0; i < cart.length; i++) {
if (cart[i].selected) {
total += cart[i].num * cart[i].price;
}
}
this.setData({
totalPrice: total.toFixed(2)
});
}
});
阅读全文