Vue3_列表渲染

测试1

测试2

clike 复制代码
<script setup >
import {ref,reactive} from 'vue'
let sub = ref("科目")

let carts = reactive(
  [
    {
      name:"可乐",
      price:3,
      number:10
    },
    {
      name:"薯片",
      price:6,
      number:12
    },
    {
      name:"炸鸡",
      price:12,
      number:2
    }
  ]
)

// 计算购物车总金额的函数
function compute(){
  let total = 0
  for(let index in carts){
    total += carts[index].price * carts[index].number
  }
  return total
}


//  从购物车中移除购物项的方法
function removeCart(index){
  carts.splice(index,1)
}

function clearCart(){
  carts.splice(0,carts.length)
}

</script>
<template>

<div>

  <h1>您的购物车如下</h1>

  <table border="1px">
    <thead>
      <tr>
        <th>序号</th>
        <th>名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>小计</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody v-if="carts.length > 0">
      <tr v-for="(cart,index) in carts" :key = "index">
        <td>{{index+1}}</td>
        <td>{{cart.name}}</td>
        <td>{{cart.price}}</td>
        <td>{{cart.number}}</td>
        <td>{{cart.price * cart.number}}</td>
        <td>
          <button @click="removeCart(index)">删除</button>
        </td>
      </tr>
    </tbody>
    <tbody v-else>
      <tr>
        <td colspan="6">
          购物车空了
        </td>
      </tr>
      
    </tbody>

  </table>
  购物车总金额 {{compute()}} 元<br>
  <button @click="clearCart()">一键清空购物车</button>

   
</div>
</template>

<style scoped>
</style>
相关推荐
leptune7 分钟前
Mac 使用 Microsoft Word 批量将 DOCX 转 PDF(保持原排版)
前端
大龄秃头程序员16 分钟前
Flutter 长列表 1 万条滑动卡顿治理:Baseline vs Optimized 可跑 Demo
前端
yingyima19 分钟前
Git 核心命令速查:掌握底层原理与实战技巧
前端
黄林晴20 分钟前
Kuikly 是什么?和KMP有什么关系?
android·前端
HokKeung21 分钟前
Git Hooks 和 Husky 怎么选
前端·前端工程化
李明卫杭州22 分钟前
Vue 3 响应式三剑客:ref、shallowRef、reactive,你真的用对了吗?
前端
触底反弹25 分钟前
🔥 JavaScript this 指向全解析:面试必考的 5 大绑定规则
前端·javascript·面试
Csvn1 小时前
TypeScript 类型守卫的 4 个实战级别:从 `filter(Boolean)` 到自定义类型谓词
前端
骑士雄师1 小时前
langchain:推荐切片策略
服务器·前端·langchain
sowhat881 小时前
Vue3+vite+Ts+pinia—第八章 生命周期
vue.js