cart.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. export default{
  2. namespaced:true,
  3. state:()=>({
  4. //购物车的数组,用来储存购物车中每个商品的信息对象
  5. //每个商品的信息对象,都包含如下六个属性
  6. //{goods_id,goods_name,goods_price,goods_count,goods_small_logo,goods_state}
  7. cart:JSON.parse(uni.getStorageSync('cart')||'[]')
  8. }),
  9. mutations:{
  10. addToCart(state,goods){
  11. const findResult = state.cart.find(x => x.goods_id===goods.goods_id)
  12. //console.log(findResult);
  13. if(!findResult){
  14. state.cart.push(goods)
  15. }
  16. else{
  17. findResult.goods_count++
  18. }
  19. //console.log(state.cart);
  20. this.commit('m_cart/saveToStorage')
  21. },
  22. saveToStorage(state){
  23. uni.setStorageSync('cart',JSON.stringify(state.cart))
  24. },
  25. //更新购物车中商品的勾选状态
  26. updateGoodsState(state,goods){
  27. const findResult = state.cart.find(x=>x.goods_id===goods.goods_id)
  28. //console.log(findResult);
  29. if(findResult){
  30. findResult.goods_state=goods.goods_state
  31. //持久化储存本地
  32. this.commit('m_cart/saveToStorage')
  33. }
  34. },
  35. //更新商品的数量
  36. updateGoodsCount(state,goods){
  37. const findResult = state.cart.find(x=>x.goods_id===goods.goods_id)
  38. if(findResult){
  39. findResult.goods_count=goods.goods_count
  40. this.commit('m_cart/saveToStorage')
  41. }
  42. },
  43. //根据ID删除对应的商品
  44. removeGoodsById(state,goods_id){
  45. state.cart = state.cart.filter(x=>x.goods_id!==goods_id)
  46. this.commit('m_cart/saveToStorage')
  47. },
  48. //更新购物车中所有 商品的勾选状态
  49. updateAllGoodsState(state,newState){
  50. state.cart.forEach(x=>x.goods_state = newState)
  51. this.commit('m_cart/saveToStorage')
  52. },
  53. //清空购物车
  54. clearCart(state){
  55. state.cart = []
  56. this.commit('m_cart/saveToStorage')
  57. }
  58. },
  59. getters:{
  60. //购物车所有商品的总数量
  61. total(state){
  62. // let c=0
  63. // state.cart.forEach(x=>c+=x.goods_count)
  64. // return c
  65. return state.cart.reduce((total,item)=>total+=item.goods_count,0)
  66. },
  67. //购物车中已勾选商品的数量
  68. checkedCount(state){
  69. return state.cart.filter(x=>x.goods_state).reduce((total,item)=> total += item.goods_count,0)
  70. },
  71. //以勾选商品的总价格
  72. checkedGoodsAmount(state){
  73. return state.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
  74. },
  75. getCart(state){
  76. return state.cart
  77. }
  78. }
  79. }