【发布时间】:2021-05-21 02:09:09
【问题描述】:
我正在尝试创建购物车按钮,问题是当新商品添加到购物车时,如果它已经存在,那么产品的数量应该增加。
addToCart(index) {
var item = this.sorted[index];
var findProduct = this.cart.find((o) => o.Name === item.Name);
if (findProduct) {
item.quantity++;
this.$set(item, 'quantity', item.quantity++)
item.totalPrice = item.quantity * item.Price;
return;
} else {
this.cart.push(item);
// this property is not available in JSON file I'm setting it later
item.quantity = 1;
item.totalPrice = item.quantity * item.Price;
}
},
这是我拥有的 JSON 格式的数据
{
"Name": "plymouth volare custom",
"Miles_per_Gallon": 19,
"Cylinders": 6,
"Displacement": 225,
"Horsepower": 100,
"Price": 3630,
"Acceleration": 17.7,
"Licensed": false,
"Date_added": "1977-01-01",
"Warehouse": "USA"
},
问题是我在 JSON 文件中没有一个名为 quantity 的 property 我稍后会在代码中将其推送到这里
item.quantity = 1
这就是为什么当数量增加时它不会在 DOM 中更新并且不会显示反应性
手动添加属性数量可以解决问题,但我无法手动添加。我必须让这个东西反应过来。
你可以在这里查看它的实时版本https://frankgarage.netlify.app/
请帮助并感谢您的时间
【问题讨论】:
-
item.quantity++ 在 $set 中,后增量不会立即发生。
-
是的,我想通了,但我期待解决方案亲爱的
-
更新items后,使用await Vue.$nextTick更新dom,希望能解决你的问题。
标签: javascript json vue.js javascript-objects vue-reactivity