Vue computed计算属性购物车实例

效果演示

对于computed的计算属性可以通过这个购物车例子来了解,笔者最近很是疲累,真的不想过多解释了,还请读者自行看代码研究。
在这里插入图片描述

参考代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.10/vue.js"></script>
  <style>
    .container {
      width: 80%;
      margin: 30px auto;
    }

    table {
      width: 100%;
      border: 1px solid blue;
      border-collapse: collapse;
    }

    th {
      height: 50px;
    }

    td{
      height: 32px;
    }

    th, td {
      border-bottom: 1px solid blue;
      text-align: center;
    }
  </style>
</head>
<body>
<div id="app">
  <div class="container">
    <table>
      <tr>
        <th>序号</th>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
      <tr v-for="iphone in goods">
        <td>{{ iphone.id }}</td>
        <td>{{ iphone.name }}</td>
        <td>{{ iphone.price }}</td>
        <td>
          <button v-bind:disabled="iphone.count === 0" v-on:click="iphone.count-=1">-</button>
          {{ iphone.count }}
          <button v-on:click="iphone.count+=1">+</button>
        </td>
        <td>
          <button v-on:click="iphone.count=0">移除</button>
        </td>
      </tr>
    </table>
    <p style="text-align:right;"> 总价:${{totalPrice}}</p>

  </div>
</div>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      goods: [{
        id: 1,
        name: 'iphone 15 128g',
        price: 5999,
        count: 1
      },
        {
          id: 2,
          name: 'iphone 15 plus 128g',
          price: 6999,
          count: 1
        },
        {
          id: 3,
          name: 'iphone 15 pro 256g',
          price: 8999,
          count: 1
        }]

    },
    computed: {
      totalPrice: function () {
        var totalP = 0;
        for (var i = 0, len = this.goods.length; i < len; i++) {
          totalP += this.goods[i].price * this.goods[i].count;
        }
        return totalP;
      }
    }
  })
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

编程初学者01

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

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

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

打赏作者

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

抵扣说明:

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

余额充值