Vue essays-data in the array changes, the page does not update

The data in the Vue array changes, but the page does not update

Problem description: When you click on the product and add it to the shopping cart, if the product already exists in the shopping cart, the number of products in the shopping cart list will not be updated at this time.

Reason: The official document explains as follows

Due to JavaScript limitations, Vue cannot detect changes in arrays and objects. There is a related discussion in Deep Responsive Principles.

solution:

this.$set(this.tableData, i, this.tableData[i])
//Vue.set(this.tableData, i, this.tableData[i])  //这样写报Vue is not defined,后续再研究

Complete code example

Product list, when you click on the product in the list, it will be added to the shopping cart list

<ul class="cookList">
  <li v-for="(goods,index) in type0Goods" :key="index" @click="addOrderList(goods)">
    <span class="foodImg"><img :src="goods.goodsImg" width="100%"></span>
    <span class="foodName">{
    
    {
    
    goods.goodsName}}</span>
    <span class="foodPrice">{
    
    {
    
    goods.price}}</span>
  </li>
</ul>

Add shopping cart code

addOrderList (goods) {
    
    
      // 商品是否已经存在于订单列表中
      let isHave = false
      for (let i = 0; i < this.tableData.length; i++) {
    
    
        if (this.tableData[i].goodsId === goods.goodsId) {
    
    
          isHave = true
          this.tableData[i].count++
          this.$set(this.tableData, i, this.tableData[i])
          // Vue.set(this.tableData, i, this.tableData[i])
          break
        }
      }

      if (!isHave) {
    
    
        // 添加商品到orderList中
        goods.count = 1
        this.tableData.push(goods)
      }
}

Shopping cart list display code

<el-table :data="tableData" border style="width:100%">
    <el-table-column prop="goodsName" label="商品名称"></el-table-column>
	<el-table-column prop="count" label="数量" width="70"></el-table-column>
	<el-table-column prop="price" label="金额" width="70"></el-table-column>
	<el-table-column label="操作" width="100" fixed="right">
    	<template>
            <el-button type="text" size="small">删除</el-button>
            <el-button type="text" size="small">增加</el-button>
        </template>
	</el-table-column>
</el-table>

Guess you like

Origin blog.csdn.net/l229568441/article/details/106845041
Recommended