1 小程序中商品求和和总价
total(){
let arr = []
const products = this.data.products
for(let i = 0;i<products.length;i++){
const goods = products[i].goods
arr = [...arr,...goods]
}
const _arr = arr.filter(item=>item.total)
return {total:_arr.reduce((sum,num)=>sum += num.total,0),
totalPrice:arr.reduce((sum,num)=>sum += num.price*num.total,0)
}
},
changeCount(e){
const {cindex,count,pindex} = e.currentTarget.dataset
const attr = `products[${pindex}].goods[${cindex}].total`
this.setData({
[attr]:count
},
()=>{
this.setData({
total:this.total().total,
totalPrice:this.total().totalPrice
})
}
)
},
<view class="total">
<view class="reduce" bindtap="changeCount" data-count="{{product.total && product.total - 1}}" data-pIndex="{{index}}" data-cIndex="{{i}}">-</view>
<view>{{product.total}}</view>
<view class="add" bindtap="changeCount" data-count="{{product.total + 1}}" data-pIndex="{{index}}" data-cIndex="{{i}}">+</view>
</view>
<view class="cart">
<view>商品数量{{total}}</view>
<view>总价{{totalPrice}}</view>
</view>
2 小程序中获取元素高度
getHeight(){
const query = wx.createSelectorQuery()
query.selectAll('.item').boundingClientRect()
query.selectViewport().scrollOffset()
query.exec(res=>{
this.setData({
itemHeights:res[0].map(item=>item.top)
})
})
},