欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vue - 案例:购物车

程序员文章站 2022-05-20 14:57:14
...

Vue - 案例:购物车

main.js

const app = new Vue({
  el: '#app',
  data: {
    books: [{
        id: 1,
        name: 'International Mobility Agent',
        date: 'Mon Nov 04 2019 19:26:59 GMT+0800 (中国标准时间)',
        price: 348.10,
        count: 4
      },
      {
        id: 2,
        name: 'Regional Metrics Developer',
        date: 'Sat Sep 28 2019 13:24:49 GMT+0800 (中国标准时间)',
        price: 867.67,
        count: 11
      },
      {
        id: 3,
        name: 'Product Applications Technician',
        date: 'Mon Nov 25 2019 01:23:04 GMT+0800 (中国标准时间)',
        price: 751.74,
        count: 2
      },
      {
        id: 4,
        name: 'Internal Identity Supervisor',
        date: 'Wed May 29 2019 23:08:32 GMT+0800 (中国标准时间)',
        price: 52.83,
        count: 3
      },
      {
        id: 5,
        name: 'Future Web Facilitator',
        date: 'Sat Sep 14 2019 13:16:19 GMT+0800 (中国标准时间)',
        price: 897.66,
        count: 5
      },
      {
        id: 6,
        name: 'Legacy Infrastructure Strategist',
        date: 'Fri Nov 08 2019 12:35:13 GMT+0800 (中国标准时间)',
        price: 851.90,
        count: 8
      },
    ]
  },
  computed: {
    totalPrice() {
      return this.books.reduce((total, cur) => {
        return total += (cur.price * cur.count);
      }, 0).toFixed(2);

    }
  },
})

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

  <div id='app'>
    <div v-if='books.length'>
      <table>
        <thead>
          <tr>
            <th> </th>
            <th>书籍名称</th>
            <th>出版日期</th>
            <th>价格</th>
            <th>购买数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for='(book, index) in books' :key='book.id'>
            <td>{{book.id}}</td>
            <td>《{{book.name}}》</td>
            <td>{{book.date}}</td>
            <td>¥{{book.price}}</td>
            <td>
              <button @click='book.count--' :disabled='book.count<1'>-</button>
              {{book.count}}
              <button @click='book.count++'>+</button>
            </td>
            <td>
              <button @click='books.splice(index, 1 )'>移除</button>
            </td>
          </tr>
        </tbody>
      </table>
      <h2>总价:{{totalPrice}}</h2>
    </div>
    <h2 v-else>购物车为空</h2>
  </div>


  <script src="../dist/vue.js"></script>
  <script src="main.js"></script>
</body>

</html>

style.css

table {
  border: 1px solid #e9e9e9;
  border-collapse: collapse;
  border-spacing: 0;
}

th,
td {
  padding: 8px 16px;
  border: 1px solid #e9e9e9;
  text-align: left;
}

th {
  background-color: #f7f7f7;
  color: #5c6b77;
  font-weight: 600;
}
相关标签: # ECMAscript 6