先看下效果:
直接上代码:
<div>
<table>
//标题
<tr>
<th class="title"></th>
<th class="title">书籍名称</th>
<th class="title">单价</th>
<th class="title">数量</th>
<th class="title">单个总价</th>
<th class="title">操作</th>
</tr>
// 循环 books 列表,渲染
<tr v-for="(item , index ) in books" :key="index">
<th>{{item.id}}</th>
<th>{{item.name}}</th>
<th>{{item.price}}</th>
<th>
//数量加减
<button @click="reduce(index)">-</button>
{{item.num}}
<button @click="addition(index)">+</button>
</th>
//单个总价
<th class="title">{{item.num * item.price}}</th>
<th>
//操作(删除)
<button @click="deletes(index)">删除</button>
</th>
</tr>
</table>
//总价
<div>总价 : {{Total}} </div>
</div>
data(){
return{
//名为books 的列表
books:[
{
id:1,
name:"Vue",
price:10.00,
num:1
},
{
id:2,
name:"React",
price:20.00,
num:1
},
{
id:3,
name:"javaScript",
price:30.00,
num:1
},
]
}
},
computed:{
//总价
Total(){
//在这里定义一个total为0,来存放他的总价
let total = 0 ;
//循环books
for (let i = 0 ; i < this.books.length ; i++ ){
//相当于 total = books每一个数量 * books每一个的价钱
total += this.books[i].num * this.books[i].price
}
return total
}
},
methods:{
//数量减
reduce(index){
//判断 books的数量是否 <= 1 ,弹出提示框,不能再减了
if ( this.books[index].num <= 1){
alert("不能在减了")
//否则 (大于1的时候) --
}else {
this.books[index].num --
}
},
//数量加
addition(index){
//数量可以一直无限的++
this.books[index].num ++
},
//删除
deletes(index){
//splice 截取下标,1个长度
this.books.splice(index , 1)
}
} ,
.title {
width:5rem;
}
版权声明:本文为weixin_49406370原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。