✅P246_商城业务-购物车-改变购物项数量
小于 1 分钟
cartList.html页面修改
为父标签自定义属性存储skuId,为加减操作设置相同的class,为数量设置class
cfmall-cart/src/main/resources/templates/cartList.html
<li>
<p th:attr="skuId=${item.skuId}">
<span class="countOpsBtn">-</span>
<span class="countOpsNum" th:text="${item.count}">5</span>
<span class="countOpsBtn">+</span>
</p>
</li>
编写加减的单击事件
$(".countOpsBtn").click(function () {
const skuId = $(this).parent().attr("skuId");
const num = $(this).parent().find(".countOpsNum").text();
location.href = "http://cart.cfmall.com/countItem?skuId=" + skuId + "&num=" + num;
});
Controller
cfmall-cart/src/main/java/com/gyz/cfmall/controller/CartController.java
/**
* 改变购物车商品数量
*
* @param skuId
* @param num
* @return
*/
@GetMapping(value = "/countItem")
public String countItem(@RequestParam(value = "skuId") Long skuId,
@RequestParam(value = "num") Integer num) {
cartService.changeItemCount(skuId, num);
return "redirect:http://cart.cfmall.com/cart.html";
}
Service
cfmall-cart/src/main/java/com/gyz/cfmall/service/impl/CartServiceImpl.java
@Override
public void changeItemCount(Long skuId, Integer num) {
//查询购物车里面的商品
CartItemVo cartItem = this.getCartItem(skuId);
cartItem.setCount(num);
BoundHashOperations<String, Object, Object> cartOps = getCartOpts();
//序列化存入redis中
String redisValue = JSON.toJSONString(cartItem);
cartOps.put(skuId.toString(), redisValue);
}