【问题标题】:Vue.js Dom is not updating on changing keys values of ObjectVue.js Dom 不会在更改 Object 的键值时更新
【发布时间】: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 文件中没有一个名为 quantityproperty 我稍后会在代码中将其推送到这里

        item.quantity = 1

这就是为什么当数量增加时它不会在 DOM 中更新并且不会显示反应性

手动添加属性数量可以解决问题,但我无法手动添加。我必须让这个东西反应过来。

你可以在这里查看它的实时版本https://frankgarage.netlify.app/

请帮助并感谢您的时间

【问题讨论】:

  • item.quantity++ 在 $set 中,后增量不会立即发生。
  • 是的,我想通了,但我期待解决方案亲爱的
  • 更新items后,使用await Vue.$nextTick更新dom,希望能解决你的问题。

标签: javascript json vue.js javascript-objects vue-reactivity


【解决方案1】:

如果购物车是您在 Dom 上显示的内容 然后将手动分配放在你推送项目的行之前

addToCart(index) {
  var item = this.sorted[index];
  var findProduct = this.cart.find((o) => o.Name === item.Name);
  if (findProduct) {
    item.quantity++;
    item.totalPrice = item.quantity * item.Price;
   this.$set(item, 'quantity', item.quantity++)
    return;
  } else {
    item.quantity = 1;
    item.totalPrice = item.quantity * item.Price;
    this.cart.push(item);
    // this property is not available in JSON file I'm setting it later
  }
},

更新项目后,使用Vue.$nextTick更新dom,希望它能解决你的问题。

【讨论】:

  • 感谢您的帮助,但这并不奏效
  • 您可以在实时网站上查看尝试添加相同产品 3 4 次,然后添加另一个产品并注意购物车图标。
  • 检查 uodate
猜你喜欢
  • 1970-01-01
  • 2018-10-06
  • 2020-08-26
  • 2020-04-30
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
相关资源
最近更新 更多