当所有购物栏被移除后, 执行v-else 语句, 显示 <div> 购物车为空</div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实现动态添加购物栏,和计算价格</title>
<style>
* { padding: 0; margin: 0 ;}
div#app { width: 500px; margin: 200px auto;}
table { border: 1px solid #ccc; border-spacing: 0;}
table thead td { font-weight: bold;}
table td { height: 50px; text-align: center; justify-content: center; border: 1px solid #ccc; font-size: 14px; width: 120px;}
.index { width: 50px;}
button { padding: 4px;}
</style>
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<tr>
<td class="index"></td>
<td class="name">书籍名称</td>
<td class="time">出版日期</td>
<td class="price">价格</td>
<td class="count">购买数量</td>
<td class="selet">操作</td>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in books">
<!-- 提取books数组中的对象的属性值 -->
<td class="index">{{item.index}}</td>
<td>{{item.name}}</td>
<td>{{item.time}}</td>
<td>{{item.price | showPrice}}</td>
<!--
1. @click="decrement(index)" 给对应的对象传实参
2. :disabled 条件成立,动态添加disabled属性,使按钮不可点击
-->
<td><button @click="decrement(index)" :disabled="item.count===1">-</button> {{item.count}} <button @click="increment(index)">+</button></td>
<td><button @click="removeHandle(index)">移除</button></td>
</tr>
</tbody>
</table>
<!-- 使用计算属性 -->
<p>总价: {{totalPrice | showPrice}}</p>
</div>
<div v-else>购物车为空</div>
</div>
<script src="../../vue.js"></script>
<script>
const app = new Vue({
el: "#app", // 绑定元素
data: {
books: [
{
index: 1,
name: '算法导论',
time: '2006-9',
price: 85.00,
count: 1
},
{
index: 2,
name: 'UNIX编程艺术',
time: '2006-2',
price: 59.00,
count: 1
},
{
index: 3,
name: '编程珠玑',
time: '2006-3',
price: 75.00,
count: 1
},
{
index: 4,
name: '代码大全',
time: '2006-10',
price: 128.00,
count: 1
}
]
},
computed: {
totalPrice() {
let totalPrice = 0 // 创建 变量
for( let i=0; i<this.books.length; i++) {
totalPrice += this.books[i].price * this.books[i].count // 总价 = 单价* 数量
}
return totalPrice // 返回数据
}
},
methods: {
decrement(index) {
this.books[index].count--
},
increment(index) {
this.books[index].count++
},
removeHandle(index) {
this.books.splice(index, 1) // 删除数组中的 index 位置的对象
}
},
// 使用过滤器 , 需与data 同层级
filters : {
showPrice(price) {
return '¥' + price.toFixed(2) // 保留两位小数点
}
}
});
</script>
</body>
</html>