vue3 computed计算属性 实现购物车

<template>
  <table border="1" cellpadding="0" cellspacing="0" style="width: 500px;margin: 0 auto;">
    <tr>
      <th><input type="checkbox" v-model="isAllChecked" />全选</th>
      <th>商品名字</th>
      <th>商品价格</th>
      <th>购买数量</th>
    </tr>
    <tr v-for="item in iceCream" :key="item.id">
      <td><input type="checkbox" v-model="item.ischecked"></td>
      <td>{
   
   { item.name }}</td>
      <td>{
   
   { item.price }}</td>
      <td>{
   
   { item.num }}</td>
    </tr>
    <tr>
      <td>总计:</td>
      <td colspan="3">{
   
   { total }}</td>
    </tr>
  </table>
</template>

<script setup>
import { reactive, computed } from "vue";

// 商品数据
var { iceCream } = reactive({
  iceCream: [
    {
      id: 99,
      name: "哈根达斯",
      price: 100,
      num: 10,
      ischecked: true
    }, {
      id: 100,
      name: "伊利",
      price: 200,
      num: 10,
      ischecked: true
    }, {
      id: 101,
      name: "蒙牛",
      price: 300,
      num: 10,
      ischecked: false
    }
  ]
})

// 全选 / 反选
var isAllChecked = computed({
  get() {
    return iceCream.every(el => el.ischecked);
  },
  set(value) {
    iceCream.forEach(el => el.ischecked = value)
  }
})

//计算总价
var total = computed(() => {
  return iceCream.reduce((cur, val) => {
    if (val.ischecked) {
      return cur + val.num * val.price
    } else {
      return cur;
    }
  }, 0)
})

</script>

猜你喜欢

转载自blog.csdn.net/qq_43770056/article/details/128818650