HTML代码:
<template>
<div id="app">
<h2>这是主页</h2>
<el-table
border
ref="multipleTable"
:data="products"
tooltip-effect="dark"
style="width: 100%"
@selection-change="handleSelectionChange" @select="select">
<el-table-column type="selection" ></el-table-column>
<el-table-column label="商品" prop="product"></el-table-column>
<el-table-column prop="price" label="单价" ></el-table-column>
<el-table-column prop="address" label="购买数量" show-overflow-tooltip>
<template slot-scope="scope">
<i class="fa fa-plus-square-o fa-2x" @click="changeNum(scope.$index, 1)"></i>
<span>{{scope.row.count}}</span>
<i class="fa fa-minus-square-o fa-2x" @click="changeNum(scope.$index,-1)"></i>
</template>
</el-table-column>
<el-table-column prop="address" label="操作" show-overflow-tooltip>
<el-button type="danger" @click="deleteGoods(scope.$index)">删除</el-button>
</el-table-column>
</el-table>
<el-row>
<h3>总价:{{allPrice}}</h3>
</el-row>
</div>
</template>扩展:
ElementUi中的el-table如何取这一行的值:
先用命名插槽:slot-scop='插槽名',然后通过scope.$index来获取下标
scope.row取的是数据每一个的元素
JS代码
export default {
name: "home",
data(){
return {
products:[],
shopCar:[],
id:''
}
},
methods:{
//全选框
handleSelectionChange(selection){
this.shopCar = selection
},
//删除商品
deleteGoods(index){
this.products.splice(index,1)
},
// 复选框
select(selection){
this.shopCar = selection
console.log(this.shopCar)
},
//加减
changeNum(index,val){
console.log(index)
this.shopCar[index].count +=val
if(this.products[index].count == 0){
this.products.splice(index,1)
}
},
},
computed:{
//计算价格
allPrice(){
return this.shopCar.reduce((sum,object)=>{
return sum+=object.price * object.count
},0)
}
},
created() {
this.products = goods
},
watch:{
products:{
handler(newValue){
console.log(newValue)
this.products= newValue
},
immediate:true,
deep:true
},
}
}
</script>扩展:
这里购物车加减可以一个事件“changeNum”,然后通过传值-1和1来直接控制数量
计算总价 :
可以使用数组的一个方法reduce方法
直接得到总价。
需要注意的是购物车加减的部分,当减为0后就将该商品删除,这里删除用的是splice来进行删除,主义的是数组用的是products(原始数据),因为渲染页面一直用的是原始数据渲染,如果使用shopCar(新数据)则不会有删除的效果。
文章展示了如何在Vue.js应用中使用ElementUI的表格组件实现商品列表,包括选择、删除、数量增减功能,并通过changeNum方法动态更新购物车商品数量。同时,利用reduce方法计算总价,当商品数量减至0时,从商品列表中移除。

1242

被折叠的 条评论
为什么被折叠?



