0
点赞
收藏
分享

微信扫一扫

24届近3年中国矿业大学自动化考研院校分析

雷亚荣 2023-09-27 阅读 28

效果演示

对于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 条评论