博客列表 >原生购物车 Vue 改写

原生购物车 Vue 改写

lucaslwk
lucaslwk原创
2022年04月18日 10:46:41301浏览

原生购物车 Vue 改写

vue购物车

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>购物车</title>
  8. <link rel="stylesheet" href="static/shoppingcart.css" />
  9. <script src="https://unpkg.com/vue@next"></script>
  10. </head>
  11. <body>
  12. <div class="box">
  13. <ul class="list" @change="update">
  14. <li>
  15. <span>品名</span><span>数量</span><span>单价</span><span>金额</span>
  16. </li>
  17. <itemlist item="手机" price="100"></itemlist>
  18. <itemlist item="电脑" price="200"></itemlist>
  19. <itemlist item="相机" price="300"></itemlist>
  20. <li>
  21. <span>总计:</span>
  22. <span class="total-num">{{totalnum}}</span>
  23. <span class="total-amount">{{totalamount}}</span>
  24. </li>
  25. </ul>
  26. <button class="account">结算</button>
  27. </div>
  28. <template id="itemlist">
  29. <li>
  30. <span class="content">{{item}}</span>
  31. <input type="number" min="1" class="num" v-model="num" />
  32. <span class="price">{{price}}</span>
  33. <span class="amount">{{payAmount}}</span>
  34. </li>
  35. </template>
  36. <script>
  37. const app = Vue.createApp({
  38. data() {
  39. return {
  40. totalnum: 0,
  41. totalamount: 0,
  42. };
  43. },
  44. methods: {
  45. update() {
  46. const numarr = [...document.querySelectorAll(".num")].map((item) =>
  47. parseInt(item.value)
  48. );
  49. this.totalnum = numarr.reduce((a, b) => a + b);
  50. const amountarr = [...document.querySelectorAll(".amount")].map(
  51. (item) => parseInt(item.innerHTML)
  52. );
  53. this.totalamount = amountarr.reduce((a, b) => a + b);
  54. },
  55. },
  56. mounted: function () {
  57. this.update();
  58. },
  59. });
  60. app.component("itemlist", {
  61. template: "#itemlist",
  62. props: ["item", "price"],
  63. data() {
  64. return {
  65. num: 1,
  66. };
  67. },
  68. computed: {
  69. payAmount() {
  70. return this.price * this.num;
  71. },
  72. },
  73. });
  74. app.mount(".box");
  75. </script>
  76. </body>
  77. </html>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议