cart.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { defineStore } from 'pinia';
  2. import cartApi from '@/sheep/api/cart';
  3. const cart = defineStore({
  4. id: 'cart',
  5. state: () => ({
  6. list: [], // 购物车列表
  7. selectedIds: [], // 已选列表
  8. isAllSelected: false, //是否全选
  9. cartSelectedTotalPrice: '0.00', // 选中项总金额
  10. }),
  11. getters: {
  12. totalPriceSelected: (state) => {
  13. let price = 0;
  14. if (!state.selectedIds.length) return price.toFixed(2);
  15. state.list.forEach((item) => {
  16. price += state.selectedIds.includes(item.id)
  17. ? Number(item.sku_price.price) * item.goods_num
  18. : 0;
  19. });
  20. return price.toFixed(2);
  21. },
  22. },
  23. actions: {
  24. // 获取购物车列表
  25. async getList() {
  26. const { data, error } = await cartApi.list();
  27. if (error === 0) {
  28. this.list = data;
  29. }
  30. },
  31. // 添加购物车
  32. async add(goodsInfo) {
  33. const { error } = await cartApi.append({
  34. goods_id: goodsInfo.goods_id,
  35. goods_num: goodsInfo.goods_num,
  36. goods_sku_price_id: goodsInfo.id,
  37. });
  38. if (error === 0) {
  39. this.getList();
  40. }
  41. },
  42. // 更新购物车
  43. async update(goodsInfo) {
  44. const { error } = await cartApi.update({
  45. goods_id: goodsInfo.goods_id,
  46. goods_num: goodsInfo.goods_num,
  47. goods_sku_price_id: goodsInfo.goods_sku_price_id,
  48. });
  49. if (error === 0) {
  50. // this.getList();
  51. }
  52. },
  53. // 移除购物车
  54. async delete(ids) {
  55. if (typeof ids === 'array') {
  56. ids = ids.join(',');
  57. }
  58. const { error } = await cartApi.delete(ids);
  59. if (error === 0) {
  60. this.selectAll(false);
  61. this.getList();
  62. }
  63. },
  64. // 选择购物车商品
  65. selectSingle(goodsId) {
  66. if (!this.selectedIds.includes(goodsId)) {
  67. this.selectedIds.push(goodsId);
  68. } else {
  69. this.selectedIds.splice(this.selectedIds.indexOf(goodsId), 1);
  70. }
  71. this.isAllSelected = this.selectedIds.length === this.list.length;
  72. },
  73. // 全选
  74. selectAll(flag) {
  75. this.isAllSelected = flag;
  76. if (!flag) {
  77. this.selectedIds = [];
  78. } else {
  79. this.list.forEach((item) => {
  80. this.selectedIds.push(item.id);
  81. });
  82. }
  83. },
  84. // 清空购物车
  85. emptyList() {
  86. this.list = [];
  87. this.selectedIds = [];
  88. this.isAllSelected = false;
  89. this.cartSelectedTotalPrice = '0.00';
  90. },
  91. },
  92. persist: {
  93. enabled: true,
  94. strategies: [
  95. {
  96. key: 'cart-store',
  97. },
  98. ],
  99. },
  100. });
  101. export default cart;