可以实现加减数量 计算总价 移除书籍 移除全部书籍之后 显示v-else “购物车为空
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue</title>
<script src="js/vue.js"></script>
<style>
</style>
</head>
<body>
<div id = "app">
<div v-if="books.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in books" :key="index">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="add(index)">+</button>
{{item.num}}
<button @click="sub(index)">-</button>
</td>
<td><button @click="remove">移除</button></td>
</tr>
</tbody>
</table>
</div>
<!-- 当书籍都移除之后 显示v-else -->
<h2 v-else>购物车为空</h2>
<h3>总价格{{tot}}</h3>
</div>
<script>
var app = new Vue({
el:"#app",
data:{
books:[
{
id:1,
name:'算法计算',
price:'10.00',
num:'1'
},
{
id:2,
name:'加勒比海盗',
price:'10.00',
num:'1'
},
{
id:3,
name:'三天光明',
price:'10.00',
num:'1'
},
{
id:4,
name:'算法计算',
price:'10.00',
num:'1'
}
]
},
methods:{
add:function(index){
this.books[index].num++;
},
sub:function(index){
this.books[index].num--;
},
//移除元素
remove(index){
this.books.splice(index,1)
}
},
//计算总价
computed:{
tot:function(){
let total = 0
for (let i=0; i< this.books.length;i++){
total += this.books[i].price * this.books[i].num
}
return total
//另一种写法 效果相同
//let total = 0
//for (let i in this.books) {
// total += this.books[i].price * this.books[i].num
//}
//return total
}
}
})
</script>
</body>
</html>