cart.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import { defineStore } from 'pinia';
  2. import CartApi from '@/sheep/api/trade/cart';
  3. const cart = defineStore({
  4. id: 'cart',
  5. state: () => ({
  6. list: [], // 购物车列表
  7. selectedIds: [], // 已选列表
  8. isAllSelected: false, // 是否全选
  9. totalPriceSelected: 0, // 选中项总金额
  10. }),
  11. actions: {
  12. // 获取购物车列表
  13. async getList() {
  14. const { data, code } = await CartApi.getCartList();
  15. if (code === 0) {
  16. this.list = data.validList;
  17. // 计算各种关联属性
  18. this.selectedIds = [];
  19. this.isAllSelected = true;
  20. this.totalPriceSelected = 0;
  21. this.list.forEach((item) => {
  22. if (item.selected) {
  23. this.selectedIds.push(item.id);
  24. this.totalPriceSelected += item.count * item.sku.price;
  25. } else {
  26. this.isAllSelected = false;
  27. }
  28. });
  29. }
  30. },
  31. // 添加购物车
  32. async add(goodsInfo) {
  33. // 添加购物项
  34. const { code } = await CartApi.addCart({
  35. skuId: goodsInfo.id,
  36. count: goodsInfo.goods_num,
  37. });
  38. // 刷新购物车列表
  39. if (code === 0) {
  40. await this.getList();
  41. }
  42. },
  43. // 更新购物车
  44. async updateCount(goodsInfo) {
  45. const { code } = await CartApi.updateCount({
  46. skuId: goodsInfo.goods_id,
  47. count: goodsInfo.goods_num,
  48. });
  49. if (code === 0) {
  50. await this.getList();
  51. }
  52. },
  53. // 更新购物车
  54. async update(goodsInfo) {
  55. const { code } = await CartApi.updateCartCount({
  56. id: goodsInfo.goods_id,
  57. count: goodsInfo.goods_num,
  58. });
  59. if (code === 0) {
  60. await this.getList();
  61. }
  62. },
  63. // 移除购物车
  64. async delete(ids) {
  65. console.log(ids)
  66. const { code } = await CartApi.deleteCart(ids.join(','));
  67. if (code === 0) {
  68. await this.getList();
  69. }
  70. },
  71. // 单选购物车商品
  72. async selectSingle(goodsId) {
  73. const { code } = await CartApi.updateCartSelected({
  74. ids: [goodsId],
  75. selected: !this.selectedIds.includes(goodsId), // 取反
  76. });
  77. if (code === 0) {
  78. await this.getList();
  79. }
  80. },
  81. // 全选购物车商品
  82. async selectAll(flag) {
  83. const { code } = await CartApi.updateCartSelected({
  84. ids: this.list.map((item) => item.id),
  85. selected: flag
  86. });
  87. if (code === 0) {
  88. await this.getList();
  89. }
  90. },
  91. // 清空购物车。注意,仅用于用户退出时,重置数据
  92. emptyList() {
  93. this.list = [];
  94. this.selectedIds = [];
  95. this.isAllSelected = true;
  96. this.totalPriceSelected = 0;
  97. },
  98. },
  99. persist: {
  100. enabled: true,
  101. strategies: [
  102. {
  103. key: 'cart-store',
  104. },
  105. ],
  106. },
  107. });
  108. export default cart;