• vue3+ts的computed属性


    购物车案例
    <template>
      <div class="container">
        <h1>总价:{{total}}</h1>
        <table border style="width: 500px">
          <thead>
            <tr>
              <th>名称</th>
              <th>数量</th>
              <th>单价</th>
              <th>价格</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in data" :key="index">
              <td>{{ item.name }}</td>
              <td>
                <button @click="add(item, false)">-</button>
                {{ item.num }}
                <button @click="add(item, true)">+</button>
              </td>
              <td>
                {{ item.price }}
              </td>
              <td>{{ item.num * item.price }}</td>
              <td><button @click="del(item,index)">删除</button></td>
            </tr>
          </tbody>
        </table>
      </div>
    </template>
    
    <script setup lang="ts">
    import { reactive, ref, computed } from "vue";
    
    interface Shops {
      name: string;
      num: number;
      price: number;
    }
    const add = (good: Shops, flag: boolean) => {
      if (flag) {
        good.num++;
      } else {
        good.num--;
      }
    };
    
    // 总价
    const total = computed<number>(() => {
      return data.reduce((prev,next)=>{
        return prev + (next.num * next.price)
      },0)
    })
    
    const del = (item:Shops,index:number) => {
      // 第一个参数是索引,第二个是删除的个数
      data.splice(index,1)
    }
    
    const singlePrice = computed(() => {});
    
    const data = reactive<Shops[]>([
      {
        name: "小飞",
        num: 1,
        price: 12,
      },
      {
        name: "小马",
        num: 1,
        price: 20,
      },
      {
        name: "小龙",
        num: 1,
        price: 30,
      },
    ]);
    </script>
    
    <style lang="scss" scoped></style>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
  • 相关阅读:
    投资风险管理
    ConcurrentHashMap
    fastdds之domain
    socket编程中服务器端常用函数以及简单实现
    服务端架构演进史
    Maven高级(黑马学习笔记)
    Linux命令之find
    MacOS升级后命令行出现xcrun: error: invalid active developer path报错信息
    ssh框架的信阳市南湾湖旅游网站的设计与开发源码
    应用缺少POI数据,如何开发地点深度信息?
  • 原文地址:https://blog.csdn.net/m0_56986233/article/details/133916466