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

Vue完成购物车

程序员文章站 2022-03-07 19:52:42
...
  1. <template>
  2. <div>
  3. <div class="cart">
  4. <h2>购物车</h2>
  5. <table>
  6. <thead>
  7. <tr>
  8. <th></th>
  9. <th>编号</th>
  10. <th>商品名称</th>
  11. <th>价格</th>
  12. <th>购买数量</th>
  13. <th>金额</th>
  14. <th>操作</th>
  15. </tr>
  16. </thead>
  17. <tbody>
  18. <tr v-for="(item, index) in books">
  19. <td>
  20. <input type="checkbox" v-model="selectBook" :value="index" />
  21. </td>
  22. <td>{{ item.id }}</td>
  23. <td>{{ item.name }}</td>
  24. <td>
  25. <span>{{ item.price }}</span>
  26. </td>
  27. <td>
  28. <button @click="sub(index, $event)" :disabled="item.count <= 1">
  29. -
  30. </button>
  31. <span>{{ item.count }}</span>
  32. <button @click="add(index, $event)" :disabled="item.count >= 10">
  33. +
  34. </button>
  35. </td>
  36. <td class="amount">{{ item.price * item.count }}</td>
  37. <td><button @click="del(index)">删除</button></td>
  38. </tr>
  39. </tbody>
  40. <tfoot>
  41. <tr>
  42. <td colspan="5">总金额:</td>
  43. <td colspan="2">
  44. <span class="total">{{ gettotal }}</span>
  45. </td>
  46. </tr>
  47. </tfoot>
  48. </table>
  49. </div>
  50. </div>
  51. </template>
  1. <script>
  2. export default {
  3. name: "App2",
  4. data() {
  5. return {
  6. books: [
  7. { id: 1, name: "细说 PHP", price: 158, active: false, count: 1 },
  8. { id: 2, name: "细说网页制作", price: 158, active: false, count: 2 },
  9. { id: 3, name: "细说 JavaScript", price: 158, active: false, count: 1 },
  10. {
  11. id: 4,
  12. name: "细说 HTML5 高级 API",
  13. price: 158,
  14. active: false,
  15. count: 1,
  16. },
  17. { id: 5, name: "细说 DOM 和 BOM", price: 158, active: false, count: 1 },
  18. ],
  19. selectBook: [],
  20. };
  21. },
  22. methods: {
  23. sub(index, event) {
  24. if (this.books[index].count > 1) {
  25. this.books[index].count--;
  26. }
  27. },
  28. add(index, event) {
  29. if (this.books[index].count < 10) {
  30. this.books[index].count++;
  31. }
  32. },
  33. del(index) {
  34. this.books.splice(index, 1);
  35. },
  36. },
  37. computed: {
  38. gettotal: {
  39. get() {
  40. let total = 0;
  41. this.selectBook.forEach(
  42. (id) => (total += this.books[id].price * this.books[id].count)
  43. );
  44. return total;
  45. },
  46. },
  47. },
  48. };
  49. </script>
  1. <style lang="less">
  2. .cart {
  3. width: 700px;
  4. margin: 0 auto;
  5. }
  6. h2 {
  7. text-align: center;
  8. }
  9. .cart table {
  10. width: 700px;
  11. border-collapse: collapse;
  12. }
  13. td,
  14. th {
  15. border: 1px solid;
  16. }
  17. </style>

Vue完成购物车