目录
1.效果图
2.vue代码
<div style="margin-top: 20px; padding: 10px 0">
<el-input-number v-model="num" :min="1" :max="1000" label="购买数量" style="width: 100px"></el-input-number>
<el-button style="margin-left: 10px; background-color: orangered; color: white; position: relative"
@click="addCart">
<span style="margin-left: 20px">加入购物车</span>
</el-button>
<el-button style="margin-left: 10px; background-color: orangered; color: white" @click="buyNow">立即购买
</el-button>
</div>
buyNow() {
if ((this.goods.store - this.num) < 0) {
this.$message({
type: 'warning',
message: '商品库存不足!'
})
return
}
API.post("/api/order", {id: this.goods.id, store: this.num}).then(res => {
// if (res.code === '0') {
if (res) {
this.$message({
type: 'success',
message: '购买成功!'
})
} else {
this.$message({
type: 'error',
message: res.msg
})
}
})
},
addCart() {
if (!this.user.id) {
this.$message({
type: 'warning',
message: '请登录!'
})
return
}
if ((this.goods.store - this.num) < 0) {
this.$message({
type: 'warning',
message: '商品库存不足!'
})
return
}
API.post("/api/cart", {goodsId: this.goods.id, count: this.num, userId: this.user.id}).then(res => {
if (res) {
this.$message({
type: 'success',
message: '加入成功!'
})
} else {
this.$message({
type: 'error',
message: res.msg
})
}
})
},
3.后端代码
@PostMapping("/api/order")//减库存接口
public Result save(@RequestBody Goods goods) {
// 库存改变,减去商品数量
Goods userGoods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getId, goods.getId()).eq(Goods::getId, goods.getId()));
if (userGoods != null) {
userGoods.setStore(userGoods.getStore()-goods.getStore());
goodsService.updateById(userGoods);
} else {
// 不同商品添加新的购物车记录
goodsService.save(goods);
}
return Result.success();
}
@PostMapping("/api/cart")//加购物车
public Result save(@RequestBody Cart cart) {
cart.setCreateTime(DateUtil.now());
// 加入购物车,相同的商品累加
Cart userCart = cartService.getOne(Wrappers.<Cart>lambdaQuery().eq(Cart::getGoodsId, cart.getGoodsId()).eq(Cart::getUserId, cart.getUserId()));
if (userCart != null) {
userCart.setCount(cart.getCount() + userCart.getCount());
cartService.updateById(userCart);
} else {
// 不同商品添加新的购物车记录
cartService.save(cart);
}
return Result.success();
}