一. 效果图如下:
二. 组件层级结构
三. 局部解析
使用父子级之间传递数据,
父级向子级传值是使用属性传递的,子级用props属性接受父级传过来的值;
子级向父级传值是通过事件传递的,子级定义一个按扭,为按钮添加事件,当点击按钮时,触发父级的自定义事件,并把值传给父级
<Counter
:qu="list.count"
:index="index"
@sub="sub"
@add="add"
></Counter>
sub(index){
if(this.productLists[index].count>0){
this.productLists[index].count--;
}
},
add(index){
this.productLists[index].count++;
},
通过splice方法来删除数据
delDate(index){
this.productLists.splice(index,1);
}
使用computed属性来计算总价
computed:{
totalPrice(){
let total=0;
this.productLists.map(list=>{
total+=list.price*list.count;
})
return total.toFixed(2);//保留两位小数
}
}
四. 整体代码:
- Counter.vue组件
<template>
<span>
<button @click="sub">-</button>
{{qu}}
<button @click="add">+</button>
</span>
</template>
<script>
export default {
props:["qu","index"], //接受父级传过来的值
methods:{
sub(){
this.$emit("sub",this.index);
},
add(){
this.$emit("add",this.index);
}
}
}
</script>
- Deleter.vue组件
<template>
<span>
<button @click="reset">删除</button>
</span>
</template>
<script>
export default {
props:["index"],
methods:{
reset(){
this.$emit("del",this.index);
}
}
}
</script>
- App.vue组件
<template>
<div>
<table>
<thead>
<tr>
<th>序号</th>
<th>商品</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(list,index) of productLists" :key="index">
<td>{{list.id}}</td>
<td>{{list.name}}</td>
<td>{{list.price}}</td>
<td>
<Counter
:qu="list.count"
:index="index"
@sub="sub"
@add="add"
></Counter>
</td >
<td>
<Deleter
:qu="list.count"
@del="delDate(index)"
></Deleter>
</td>
</tr>
<tr>
<td colspan="5">总价:{{totalPrice}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import Counter from "./components/Counter"
import Deleter from "./components/Deleter"
export default {
components:{Counter,Deleter},
data(){
return{
productLists:[
{
id:1,
name:"小米手机",
price:2600,
count:0
},
{
id:2,
name:"苹果手机",
price:2600,
count:0
},
{
id:3,
name:"vivo手机",
price:2600,
count:0
},
{
id:4,
name:"华为手机",
price:2600,
count:0
}
]
}
},
methods:{
sub(index){
if(this.productLists[index].count>0){
this.productLists[index].count--;
}
},
add(index){
this.productLists[index].count++;
},
delDate(index){
this.productLists.splice(index,1);
}
},
computed:{
totalPrice(){
let total=0;
this.productLists.map(list=>{
total+=list.price*list.count;
})
return total.toFixed(2);//保留两位小数
}
}
}
</script>
<style>
*{
margin:0px;
padding:0px;
}
table{
border-collapse: collapse;/**收缩边框 */
margin:50px auto;
}
tr,th,td{
border:1px solid #444;
width:100px;
height:25px;
text-align:center;
line-height:30px;
}
</style>