微信小程序App中的值
detail.js中点击加入购物车
onAddCart(){
// 3.1获取商品对象
const obj = {}
obj.iid = this.data.iid
obj.imageURL = this.data.topImages[0]
obj.title = this.data.baseInfo.title
obj.desc = this.data.baseInfo.desc
obj.price = this.data.baseInfo.realPrice
app.addToCart(obj)
}
app.js存入全局变量cartList数组
App({
globalData: {
cartList: []
},
// 1.加入购物车操作
addToCart(obj){
const oldInfo = this.globalData.cartList.find( item => item.iid === obj.iid )
if(oldInfo){
oldInfo.count += 1
}else{
obj.count = 1
obj.checked = true
this.globalData.cartList.push(obj)
}
}
})
cart.js里面
const app = getApp()
Page({
data: {
cartList: [],
isSelectAll: true,
totalPrice: 0,
totalCounter: 0
},
// 方法1、统计totalPrice和totalCount
changeData() {
let counter = 0
let totalPrice = 0
for(let item of this.data.cartList){
if(item.checked){
counter++
totalPrice += item.price * item.count
}
}
this.setData({
totalCounter: counter,
totalPrice: totalPrice
})
},
onLoad: function(options) {
// 1.第一次加载数据
this.setData({
cartList: app.globalData.cartList
})
// 2.cart-list-item里面check-icon发生改变
app.changeGoodsState = (index,goods) => {
// 1.修改某一项
this.setData({
[`cartList[${index}]`]: goods
})
// 2.修改bottom-bar里面的值
const selectAll = !this.data.cartList.find(item => !item.checked)
this.setData({
isSelectAll: selectAll
})
this.changeData()
}
},
// 1.进入页面
onShow: function() {
// 1.1读取数据
this.changeData()
// 1.2设置标题
wx.setNavigationBarTitle({
title: `购物车(${this.data.cartList.length})`,
})
},
// 点击全选
onSelectAll(){
if(this.data.isSelectAll){//true全部选中
this.data.cartList.forEach(item => {
item.checked = false
})
this.setData({
cartList: this.data.cartList,
isSelectAll: false
})
}else{//某些没有选中
this.data.cartList.forEach(item => item.checked = true)
this.setData({
cartList: this.data.cartList,
isSelectAll: true
})
}
}
})
cart-list-item.js
const app = getApp()
Component({
methods: {
onCheckClick(e){
// 1.查找到对应的商品
const goods = app.globalData.cartList.find(item => item.iid == this.properties.goods.iid)
goods.checked = !goods.checked
// 2.获取当前商品的index
const index = e.currentTarget.dataset.index
// 3.回调(重点)
app.changeGoodsState(index,goods)
}
}
})