vue实现一个购物车页面

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
          <th>Quantity</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in items" :key="index">
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <input type="number" v-model.number="item.quantity" @input="updateQuantity(index, item.quantity)">
          </td>
          <td>
            <button @click="removeFromCart(index)">Remove</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div>
      Total: {{ total }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1', price: 9.99, quantity: 1 },
        { id: 2, name: 'Item 2', price: 19.99, quantity: 2 },
        { id: 3, name: 'Item 3', price: 29.99, quantity: 3 }
      ]
    }
  },
  computed: {
    total() {
      return this.items.reduce((sum, item) => sum + item.price * item.quantity, 0)
    }
  },
  methods: {
    updateQuantity(index, quantity) {
      this.items[index].quantity = quantity
    },
    removeFromCart(index) {
      this.items.splice(index, 1)
    }
  }
}
</script>

<style>
table {
  border-collapse: collapse;
  width: 100%;
  margin-top: 20px;
}

th, td {
  border: 1px solid gray;
  padding: 10px;
  text-align: left;
}
</style>

上面的代码使用了Vue的v-for指令,将购物车中的商品循环渲染到表格中。同时使用了v-model指令绑定数量的输入值,并使用updateQuantity()方法更新数量。使用removeFromCart()方法实现从购物车中移除商品。最后使用computed属性计算购物车的总价。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

终将老去的穷苦程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值