axdbk  

应用场景,当购物车添加了一个商品时,购物车的总数和其总价格需重新计算

这里有4个商品,现在对任意一个进行添加或删除总价格和总数量都要进行变化

1. 定义变量

dataList: [
    {name: '圆面', price: 5, num: 0},
    {name: '宽面', price: 12.3, num: 0},
    {name: '挂面', price: 6, num: 0},
    {name: '方便面', price: 7, num: 0}
],
totalPrice: 0, // 总价
totalWeight: 0, // 总重量

2. 渲染页面

<view class="noodle-list">
                <view class="list" v-for="(item, index) in dataList" :key="index">
                    <view class="list-info flex-a">
                        <image src="../../../static/images/cover.png" mode="aspectFill"></image>
                        <view class="noodle-info">
                            <view class="noodle-name">{{ item.name }}</view>
                            <view class="count-box flex-s">
                                <view class="weight">¥:{{ item.price }}/斤</view>
                                <view class="select flex-c" @tap="count(2, item)" v-if="item.num === 0">+</view>
                                <view class="count flex-a" v-else>
                                    <view class="reduce" @tap="count(1, item)">-</view>
                                    <view class="num">{{ item.num }}</view>
                                    <view class="add" @tap="count(2, item)">+</view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="total-box flex-s">
                <view class="total-price flex-a">
                    <text>合计:</text>
                    <view class="total" v-if="totalPrice && totalWeight">
                        <view class="total-weight">{{ totalWeight }}(斤)</view>
                        <view class="price">¥{{ totalPrice }}</view>
                    </view>
                    <view v-else>请添加商品</view>
                </view>
                <view class="buy" @tap="buy">下单</view>
            </view>

3. 添加/减少

count(item, data) {
    if(item === 1) {
      if(data.num > 0) {
          data.num --;
        }
    }else if(item === 2) {
      data.num ++;
    }
},    

 

4. watch监听

dataList: {
    immediate: true,
    deep: true,
    handler(newList) {
    // newList是改变后的新数组
    this.totalPrice = 0;
    this.totalWeight = 0;
    newList.forEach(res => {
      this.totalPrice += res.num * res.price
      this.totalWeight += res.num
    })
  }
}

 

 

 

 

  

 

 


posted on 2023-02-20 16:00  前端真难123  阅读(95)  评论(0编辑  收藏  举报