Vue中简单版的购物车实例

需要实现的功能:

点击"+"按钮,总价增加,点击"-"按钮总价减少,点击移除,移除当列。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#app{
				margin-left:500px;
			}
			table {
				border: 2px solid red;
				width: 500px;
				border-collapse: collapse;
			}
		
			td {
				border: 2px solid red;
				padding-top: 10px;
			}
			.a{
				margin-top: 20px;
				margin-left:350px;
				font-size: 20px;
			}
			tr{
				text-align: center;
			}
		</style>
	</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>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(values,index) in contents">
            <td>{{values.id}}</td>
            <td>{{values.name}}</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 class="a">总价格:<span>{{totalPrice | formatPrice}}元</span></div>
  </div>
  <script src="vue.js"></script>
  <script type="text/javascript">
     new Vue({
      el: '#app',
      data: {
        contents: [
          {id: 1,name:'《语文》',price: 200,count: 1},
          {id: 2,name:'《数学》',price: 100,count: 1},
          {id: 3,name:'《英语》',price: 160,count: 1},
          {id: 4,name:'《体育》',price: 500,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)
        }
      },
    })
  </script>
</body>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值