javascript - vuejs+elementui 購物車價格計算,點擊加減號修改數量總價都不會改變,但是計算執行了
問題描述
一個商品下單的功能查出所有商品,點擊下單,然后把下單的商品加入購物車,購物車是不用保存的商品可以修改數量,計算總價,現在我method里面的計算執行了,但是頁面點擊加減號的時候,數量和總價就是不會變,查詢出來的數據列表里面,沒有數量和總價這兩個字段,這里是我自己定義的
<el-table-column label='數量' ><template scope='scope'> <el-input v-model='scope.row.count' :value='scope.row.count' @change='changeCount(scope.row)' :min='1' :max='scope.row.num'> <el-button slot='prepend' @click='changeQuantity(scope.row,-1)'><i class='el-icon-minus'></i></el-button> <el-button slot='append' @click='changeQuantity(scope.row,1)'><i class='el-icon-plus'></i></el-button> </el-input> <br /> <span style='color:#999;display: block; text-align: center;'>庫存{{scope.row.num}}件</span></template> </el-table-column> <el-table-column prop='price' label='單價' width='100'></el-table-column> <el-table-column prop='totalPrice' label='總價' v-model='cartListData.totalPrice'></el-table-column>
count: undefined,totalPrice: 0,
//下單商品列表getCartData() {this.$axios({url: this.path + ’product/getByList’,method: ’get’,params: this.cartListQuery,transformRequest: [function(params) { let ret = ’’ for(let it in params) {ret += encodeURIComponent(it) + ’=’ + encodeURIComponent(params[it]) + ’&’ } return ret}],headers: { ’Content-Type’: ’application/x-www-form-urlencoded’} }) .then((res) => {this.cartNum //下單商品的長度this.cartListData = res.data;this.cartListData.forEach(function(data,index){ data.count = 1; //默認一個商品 data.totalPrice= (data.price * parseInt(data.count)).toFixed(2); //商品總價});}) .catch((err) => {console.log(err); }) }, //加減號 changeQuantity(row, type){ if( type > 0 ){row.count++; }else{row.count > 1 ? row.count--: row.count = 1; } this.changeCount(row); }, //數量文本框值改變 changeCount (row) {if(null == row.count || row.count == ''){ row.count=1;}row.totalPrice = (row.count * row.price).toFixed(2);//保留兩位小數 console.log(row.totalPrice+' = '+ row.count +' * '+ row.price)//增加商品數量也需要重新計算商品總價 },
問題解答
回答1:changeCount (row) {const index = this.cartListData.indexOf(row);this.cartListData.splice(index,1,row); //需要更新一下table數據if(null == row.count || row.count == ''){ row.count=1;}row.totalPrice = (row.count * row.price).toFixed(2);//保留兩位小數 console.log(row.totalPrice+' = '+ row.count +' * '+ row.price)//增加商品數量也需要重新計算商品總價 }回答2:
第一個問題,你的問題代碼截圖不完整
第二個問題,你的總價的v-model是cartListData的totalPrice,而你的method里面設置的是row的totalPrice,你確定你的cartListData與row是同一個對象?
