使用方法 :
- toFixed(2) 保留俩位小数
- splice(index,howmany) 删除商品 index 规定添加删除的位置 ,howmany 删除几个
- border-collapse: collapse; 边界折叠: 折叠
- border-spacing: 0; 边框间距 0
- 添加 disabled 将按钮在某一条件下固定(如数量小于1时,将不能执行按钮点击操作 通过 :disabled=‘item.count===1’ 将按钮锁定)
- v-for v-else v-bind @click 的使用
- html 代码
<div id="app">
<div v-if='books.length'>
<table>
<thead>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</thead>
<tbody>
<tr v-for='(item,index) in books' :key='item.id'>
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price*item.count|showPrice}}</td>
<td>
<button @click="decrement(index)" :disabled='item.count===1'>-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td><button @click='haddleRemove(index)'>删除</button></td>
</tr>
</tbody>
</table>
<h4> 共 {{totalCount}} 件商品 总价: {{totalPrice|showPrice}} </h4>
</div>
<div v-else>购物车已经空啦!</div>
</div>
- 引入js和css文件(js文件在body里引入 ,css文件在head里面引入)
<script src="../js/vue.js"></script>
<script src="./main.js"></script>
<link rel="stylesheet" href="./index.css">
- css 样式代码:
table{
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th,td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th{
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}
- js 代码
const app = new Vue({
el: '#app',
data: {
books: [
{
id: 1,
name: '《算法导论》',
date: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: '《UNIX编程艺术》',
date: '2006-2',
price: 59.00,
count: 1
},
{
id: 3,
name: '《编程珠玑》',
date: '2008-10',
price: 39.00,
count: 1
},
{
id: 4,
name: '《代码大全》',
date: '2006-3',
price: 128.00,
count: 1
},
]
},
methods: {
increment(index) {
this.books[index].count++
},
decrement(index) {
this.books[index].count--
},
haddleRemove(index) {
this.books.splice(index, 1)
},
},
computed: {
totalPrice() {
let total = 0
for (let i = 0; i < this.books.length; i++) {
total += this.books[i].price * this.books[i].count
}
return total
},
totalCount() {
let count = 0
for (let i = 0; i < this.books.length; i++) {
count += this.books[i].count
}
return count
}
},
filters: {
showPrice(value) {
return '¥' + value.toFixed(2)
}
}
})
- 效果图:
 注: 小技巧 使用{{item.price*item.count}} 来计算单个商品的总价并显示在页面中
|