购物车页面,根据选中的商品来动态更改总价格

发布时间 2023-12-13 18:24:49作者: __fairy

一、前端代码

首先引入:

import { ref, computed } from ' vue '
  1. checked数组更新为响应式引用,使用ref()函数:
    • const checked = ref([])
  2. 使用v-modelchecked数组绑定到van-checkbox组件上:
    • <van-checkbox :name="item.cartID" checked-color="#ff5d4e" v-model="checked"></van-checkbox>
  3. 修改totalPrice的计算方式,只考虑选中的商品:
    • // 勾选商品,计算出合计数
      const totalPrice = computed(() => {
          // 通过筛选 shoppingData 数组,只保留 checked 数组中包含的商品项,即选中的商品项。
          const selectedItems = shoppingData.value.filter(item => checked.value.includes(item.cartID));
      
          // 使用 Array.reduce() 方法对选中的商品项进行迭代。在每次迭代中,
          // 从商品项中获取价格 (item.product.price) 和数量 (item.quantity),
          // 然后计算出该商品项的小计 (price * quantity)。
          return selectedItems.reduce((accumulator, item) => {
              const price = parseFloat(item.product.price);
              const quantity = item.quantity;
              const itemTotal = price * quantity;
              
              // 将所有商品项的小计累加到 accumulator 变量中,并将其作为计算属性 totalPrice 的返回值。
              return accumulator + itemTotal;
          }, 0);
      });
  4. 更新模板以显示更新后的totalPrice
    • 合计:<span style="color: #84301c;">¥{{ totalPrice }}</span>

二、实现效果: