前端代码:
<li v-for="(itme,index) in GoodList">
<div class="pic">
<a href="#"><img v-lazy="'/static/'+itme.productImage" alt=""></a>
</div>
<div class="main">
<div class="name">{{itme.productName}}</div>
<div class="price">{{itme.salePrice}}</div>
<div class="btn-area">
<a href="javascript:;" class="btn btn--m" @click="addCart(itme.productId)">加入购物车</a>
</div>
</div>
</li>
addCart(productId){
axios.post('/goods/addCart',{productId:productId}).then((res)=>{
if(res.status==0){
alert("添加成功");
}else{
alert("msg:"+res.msg);
}
})后端代码:///加入购物车router.post("/addCart", function(req, res, next) { var userId = "100000077"; var productId = req.body.productId; var User = require('../models/user'); User.findOne({ userId: userId }, function(err, userDoc) { if(err) { res.json({ status: "1", msg: err.message }) } else { if(userDoc) { console.log("userDoc:" + userDoc); let goodsItem = ''; userDoc.cartList.forEach(function(item) { if(item.productId == productId) { goodsItem = item; item.productNum++; } }); if(goodsItem) { userDoc.save(function(err2, doc2) { if(err2) { res.json({ status: "1", msg: err2.message }); } else { res.json({ status: "0", msg: "", result: "suc" }); } }) } else { Goods.findOne({ productId: productId }, function(err1, doc) { if(err1) { res.json({ status: "1", msg: err1.message }); } else { if(doc) { newobj = { //新创建一个对象,实现转换mongoose不能直接增加属性的坑 productId: doc.productId, producName: doc.producName, salePrice: doc.salePrice, productName: doc.productName, productImage: doc.productImage, productNum: "1", checked: "1", } userDoc.cartList.push(newobj); userDoc.save(function(err2, doc2) { if(err2) { res.json({ status: "1", msg: err2.message }); } else { res.json({ status: "0", msg: "", result: "suc" }); } }) } } }); } } } });});
添加回答
举报
0/150
提交
取消