【发布时间】:2018-03-14 17:59:19
【问题描述】:
我遇到了一个问题。在我深入研究之前,让我给你一些细节。 我正在学习,所以这不是一个真正的项目。其次,该应用程序基于 youtube (https://www.youtube.com/watch?v=56TizEw2LgI&list=PL55RiY5tL51rajp7Xr_zk-fCFtzdlGKUp) 上的 acadmind 视频教程中的教程,这里是 github 链接 (https://github.com/pin2plane/Academind-nodejs-shopping-cart) 该教程是使用 hbs 模板框架构建的。我正在尝试使用 PUG 构建相同的项目。我遇到了一个迭代问题:
我们有 cart.add 函数:
module.exports = function Cart(oldCart) {
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0
this.add = function (item, id) {
//If the item exists in the stored item, go to increase the qty, price of that item line
//Also update the totalQty and totalPrice
var storedItem = this.items[id];
//if the item not there, then add the item to the empty items object
if (!storedItem) {
storedItem = this.items[id] = { item: item, qty: 0, price: 0 };
}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.item.price;
};
关注这一行:
storedItem = this.items[id] = { item: item, qty: 0, price: 0 };
如您所见,object属性由item[object, object]、qty和price组成
shopping-cart.hbs 视图是这样的:
{{# if products }}
<div class="row">
<div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3">
<ul class="list-group">
{{# each products }}
<li class="list-group-item">
<span class="badge">{{ this.qty }}</span>
<strong>{{ this.item.title }}</strong>
<span class="label label-success">${{ this.price }}</span>
<div class="btn-group">
<button class="btn btn-primary btn-xs dropdown-toggle" type="button" data-toggle="dropdown">Action <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="/reduce/{{this.item._id}}">Reduce by 1</a></li>
<li><a href="/remove/{{this.item._id}}">Remove All</a></li>
</ul>
</div>
</li>
{{/each}}
</ul>
</div>
</div>
我的问题是显示减少 1 并全部删除的下拉按钮。
这是我的 pug 文件(产品从路由处理程序传递到视图)
div.row
div.col-lg-6.clearfix.offset-2.border
p.badge.badge-warning.float-right Quantity #{product.qty}
p Total price: #{product.price}  
each val in product
p #{val.title}
p DB Item ID : #{val._id}
.dropdown
button.btn.btn-primary.dropdown-toggle(type='button', data-toggle='dropdown', aria-haspopup='true', aria-expanded='false') Action
ul.dropdown-menu
li
a.dropdown-item(href='#') Reduce By 1
li
a.dropdown-item(href='#') Remove All
如您所见,迭代遍历 {item :item, qty :, price: } 但是因为我需要访问 item._id (val._id),所以我不能将按钮移到这个 div 之外,除非有另一种方法来获取 item id,这样我就可以将它传递给我的路由处理程序来处理减 1 并删除所有功能。
正如我在开始时所说,代码 100% 与 hbs 一起工作,所以它不是路线或快递,这是纯粹的哈巴狗问题,迭代工作正常,因为我能够访问购物车对象中的每个产品并显示标题、ID 和所有内容
它正在访问 id 并将其传递给我过去两天试图弄清楚如何将 id 传递给按钮而不迭代对象但无法弄清楚的按钮
如果有一个哈巴狗忍者在如何完成此操作方面有经验,非常感谢向我展示我做错了什么或如何正确设置它以匹配 hbs 文件提供的相同功能.
干杯
【问题讨论】: