博客列表 >Vue 购物车页面计算功能的实现

Vue 购物车页面计算功能的实现

zg的php学习
zg的php学习原创
2021年11月03日 17:58:55452浏览

Vue 购物车页面计算功能的实现

  1. <template>
  2. <div>
  3. <table class="cart">
  4. <caption>
  5. 购物车
  6. </caption>
  7. <thead>
  8. <th></th>
  9. <th>编号</th>
  10. <th>商品名称</th>
  11. <th>价格</th>
  12. <th>数量</th>
  13. <th></th>
  14. </thead>
  15. <tbody>
  16. <tr v-for="(row, index) in cartlist" :key="index">
  17. <td><input type="checkbox" v-model="row.checkbox" /></td>
  18. <td>{{ row.id }}</td>
  19. <td>{{ row.name }}</td>
  20. <td>{{ row.price.toFixed(2) }}</td>
  21. <td>
  22. <button @click="row.count--" :disabled="row.count <= 1">-</button>
  23. {{ row.count }}
  24. <button @click="row.count++">+</button>
  25. </td>
  26. <td><a href="#" @click.prevent="del(index)">删除</a></td>
  27. </tr>
  28. </tbody>
  29. <tfoot>
  30. <tr>
  31. <td colspan="3">总价</td>
  32. <td colspan="3">¥{{ totalPrice }}</td>
  33. </tr>
  34. </tfoot>
  35. </table>
  36. </div>
  37. </template>
  38. <script>
  39. const cartArr = [
  40. { id: 1, checkbox: false, name: "《细说PHP》", price: 10, count: 1 },
  41. { id: 2, checkbox: true, name: "《细说网页制作》", price: 10, count: 1 },
  42. {
  43. id: 3,
  44. checkbox: true,
  45. name: "《细说JavaScript 语言》",
  46. price: 10,
  47. count: 1,
  48. },
  49. { id: 4, checkbox: true, name: "《细说DOM 和BOM》", price: 10, count: 1 },
  50. {
  51. id: 5,
  52. checkbox: false,
  53. name: "《细说Ajax 与jQuery》",
  54. price: 10,
  55. count: 1,
  56. },
  57. { id: 6, checkbox: true, name: "《细说HTML5 高级API》", price: 10, count: 1 },
  58. ];
  59. export default {
  60. name: "app",
  61. data() {
  62. return {
  63. cartlist: cartArr,
  64. };
  65. },
  66. computed: {
  67. totalPrice: {
  68. get() {
  69. return this.cartlist
  70. .filter((row) => row.checkbox)
  71. .reduce((p, c) => {
  72. return (p += c.price * c.count);
  73. }, 0)
  74. .toFixed(2);
  75. },
  76. },
  77. },
  78. methods: {
  79. del(index) {
  80. this.cartlist.splice(index, 1);
  81. },
  82. },
  83. };
  84. </script>
  85. <style>
  86. .cart {
  87. width: 500px;
  88. border-collapse: collapse;
  89. text-align: center;
  90. }
  91. .cart td,
  92. .cart th {
  93. border: 1px solid black;
  94. padding: 2px 3px;
  95. }
  96. .cart tbody tr:hover {
  97. background-color: #e3e3e3;
  98. }
  99. </style>

购物车

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议