Vue购物车案例(初学版)

本文介绍了如何使用Vue.js框架构建一个初级版本的购物车应用。通过实例代码讲解了Vue组件化思想,以及如何处理数据绑定和事件监听,实现商品的增删及数量修改功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车</title>
  <link rel="stylesheet" href="//unpkg.com/layui@2.6.8/dist/css/layui.css">
</head>
<body>
  <div id="app">
    <div v-if="contents.length">
      <table class="layui-table" lay-size="lg">
        <thead>
          <tr>
            <th></th>
            <th>书籍名称</th>
            <th>出版日期</th>
            <th>价格</th>
            <th>购买数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(values,index) in contents">
            <td>{{values.id}}</td>
            <td>{{values.name}}</td>
            <td>{{values.date}}</td>
            <td>{{values.price | formatPrice}}</td>
            <td>
              <button @click="sub(index)" class="layui-btn" :disabled="values.count <= 1">-</button>
              <span>{{values.count}}</span>
              <button @click="add(index)" class="layui-btn">+</button>
            </td>
            <td>
              <button class="layui-btn layui-btn-radius layui-btn-danger" @click="removeHandle(index)">移除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <h1 v-else>
      购物车为空
    </h1>
    <div>
      总价格:<span>{{totalPrice | formatPrice}}</span>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        contents: [
          {id: 1,name: '《算法导论》',date: '2006-9',price: 85,count: 1},
          {id: 2,name: '《UNIX编程艺术》',date: '2006-2',price: 59,count: 1},
          {id: 3,name: '《编程珠玑》',date: '2008-10',price: 39,count: 1},
          {id: 4,name: '《代码大全》',date: '2006-3',price: 128,count: 1},
        ]
      },
      methods: {
        add(index) {//增加购物车项目数量
          this.contents[index].count ++
        },
        sub(index) {//减少购物车项目数量
          this.contents[index].count --
        },
        removeHandle(index) {//删除购物车项目
          this.contents.splice(index,1)
        }
      },
      computed: {
        totalPrice() {//购物车总价格
          return this.contents.reduce(function(pre,n) {
            return pre + n.count * n.price
          },0)
        }
      },
      filters: {
        formatPrice(price) {
          return '¥' + price.toFixed(2)
        }
      }
    })
  </script>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

boboj1

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

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

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

打赏作者

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

抵扣说明:

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

余额充值