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

vue购物车练习

程序员文章站 2022-03-24 09:37:00
...
  1. <template>
  2. <div>
  3. <h1>购物车</h1>
  4. <table border="1px" cellspacing="0">
  5. <tr>
  6. <th></th>
  7. <th>编号</th>
  8. <th>商品名称</th>
  9. <th>价格</th>
  10. <th>购买数量</th>
  11. <th>操作</th>
  12. </tr>
  13. <tr v-for="(item,index) in cartList" :key="item.id">
  14. <td><input type="checkbox" v-model="item.checked"></td>
  15. <td>{{item.id}}</td>
  16. <td>{{item.name}}</td>
  17. <td>¥{{item.price}}</td>
  18. <td>
  19. <button @click="item.count--" :disabled="item.count<=0">-</button>
  20. {{item.count}}
  21. <button @click="item.count++">+</button>
  22. </td>
  23. <td><a href="#" @click.prevent="del(index)" >删除</a></td>
  24. </tr>
  25. <tr>
  26. <td colspan="3">总计:</td>
  27. <td colspan="3">¥{{totalPrice}}</td>
  28. </tr>
  29. </table>
  30. </div>
  31. </template>
  32. <script>
  33. export default {
  34. name: 'App',
  35. data(){
  36. return{
  37. cartList: [
  38. {id:1, checked:false, name:'《细说PHP》', price:10, count:1},
  39. {id:2, checked:false, name:'《细说网页制作》', price:20, count:1},
  40. {id:3, checked:false, name:'《细说JavaScript语言》', price:40, count:1},
  41. {id:4, checked:false, name:'《细说DOM和BOM》', price:50, count:1},
  42. {id:5, checked:false, name:'《细说Ajax与jQuery》', price:60, count:1},
  43. {id:6, checked:false, name:'《细说HTML5高级API》', price:70, count:1},
  44. ]
  45. }
  46. },
  47. methods:{
  48. del(id){
  49. this.cartList.splice(id,1)
  50. }
  51. },
  52. computed: {
  53. totalPrice(){
  54. let sum =0
  55. for(let item of this.cartList) {
  56. console.log(item)
  57. if(item.checked) {
  58. sum += item.price * item.count;
  59. }
  60. }
  61. return sum;
  62. }
  63. },
  64. }
  65. </script>
  66. <style>
  67. h1 {
  68. text-align: center;
  69. margin-bottom: 20px;
  70. }
  71. table{
  72. margin: 0 auto;
  73. }
  74. button{
  75. margin: 0 5px;
  76. }
  77. </style>