cart.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 update(goodsInfo) {
  45. const { code } = await CartApi.updateCartCount({
  46. id: goodsInfo.goods_id,
  47. count: goodsInfo.goods_num,
  48. });
  49. if (code === 0) {
  50. await this.getList();
  51. }
  52. },
  53. // 移除购物车
  54. async delete(ids) {
  55. let idsTemp = '';
  56. if (Array.isArray(ids)) {
  57. idsTemp = ids.join(',');
  58. } else {
  59. idsTemp = ids;
  60. }
  61. const { code } = await CartApi.deleteCart(idsTemp);
  62. if (code === 0) {
  63. await this.getList();
  64. }
  65. },
  66. // 单选购物车商品
  67. async selectSingle(goodsId) {
  68. const { code } = await CartApi.updateCartSelected({
  69. ids: [goodsId],
  70. selected: !this.selectedIds.includes(goodsId), // 取反
  71. });
  72. if (code === 0) {
  73. await this.getList();
  74. }
  75. },
  76. // 全选购物车商品
  77. async selectAll(flag) {
  78. const { code } = await CartApi.updateCartSelected({
  79. ids: this.list.map((item) => item.id),
  80. selected: flag
  81. });
  82. if (code === 0) {
  83. await this.getList();
  84. }
  85. },
  86. // 清空购物车。注意,仅用于用户退出时,重置数据
  87. emptyList() {
  88. this.list = [];
  89. this.selectedIds = [];
  90. this.isAllSelected = true;
  91. this.totalPriceSelected = 0;
  92. },
  93. },
  94. persist: {
  95. enabled: true,
  96. strategies: [
  97. {
  98. key: 'cart-store',
  99. },
  100. ],
  101. },
  102. });
  103. export default cart;