Vue data rendering problem

Scenario: In the shopping cart, you can enter the quantity of the product, but when illegal data is entered, the quantity of the product will be automatically changed to 1.

However, it is found that after entering illegal data, the number of commodities in the view is illegal data instead of 1.

  <div class="count">
          <span @click="dec(item.id)">-</span>
          <input type="text" :value="item.goods_count" @change="number(item.id,$event)" />
          <span @click="add(item.id)">+</span>
        </div>
  number(id, e) {
      // 1. 将输入的新值转化为整数
      const parseResult = parseInt(e.target.value)
      // 2. 如果转换的结果不是数字,或小于1,则强制 number 的值等于1
      if (isNaN(parseResult) || parseResult < 1) {
        this.$emit('numChange', id, 1)
        return
      }
}

 app.view:

<div class="app-footer">
      <Footer :count="count" :price="price" :isfull="full" @onCheckBoxChange="CheckBoxChange"></Footer>
    </div>
  numChange(id, val) {
      this.list[id - 1].goods_count = +val
    }

When you click on any check event, increase or decrease the number of items, the view will be refreshed with the number in the data requested from the service area (mostly the number is 1). What's interesting is that after clicking the increase or decrease event, inputting a negative number can correctly correct the illegal data, and it is only valid for the item bound to the click event.

After investigation, it was found that most of the items were 1 for the data requested from the server, and after we input illegal data on the view, the component processed the illegal data as 1 and returned to app.vue, because the data itself is 1, equal to no change, so it will not be re-rendered, and the illegal data we entered will remain on the view.

solution:

First assign the number of items to 0 (because it is impossible to be 0 in the shopping cart), and then assign the number of items to 1 to re-render.

    numChange(id, val) {
      if (+val === 1) {
        this.list[id - 1].goods_count = 0
        this.list[id - 1].goods_count = 1
      }
      this.list[id - 1].goods_count = +val
    }

Guess you like

Origin blog.csdn.net/qq_51588894/article/details/129975705