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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM