zoukankan      html  css  js  c++  java
  • Vue随笔——Vue数组中数据改变,页面不更新

    Vue数组中数据改变,页面不更新

    问题描述:点击商品,加入购物车时,如果购物车中已经存在该商品,此时购物车列表的商品数量不更新。

    原因:官方文档解释如下

    由于 JavaScript 的限制,Vue 不能检测数组和对象的变化。深入响应式原理中有相关的讨论。

    解决方案:

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

    完整代码示例

    商品列表,点击列表中的商品时,会添加到购物车列表中

    <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>

    添加购物车代码

    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)
        }
    }

    购物车列表展示代码

    <el-table :data="tableData" border style="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>

     

  • 相关阅读:
    电子工程师对程序员的一番心里话(转载)
    一个程序员的一生(转载)
    程序人生中的十个感悟...
    谈计算机软件发展观念(转载)
    ASP.NET 2.0服务器控件开发精要(转载)
    一个老程序员的心里话(转载)
    hdu 1316 斐波那契数
    hdu 3117 斐波那契数列
    hdu 1239 素数水题
    hdu 2256 神奇的矩阵
  • 原文地址:https://www.cnblogs.com/henry-blog/p/13155438.html
Copyright © 2011-2022 走看看