最终效果如下图:
完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv=" X-UA-Compatible" content="ie=edge">
<title>42-图书购物车案例-事件完成</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js" ></script>
<style>
table,td,th{
border: 1px solid #000;
/* 设置表格线条粗细,形状,颜色 */
}
table{
border-collapse: collapse; /* 作用:表格边框折叠,没有间隙 */
/* collapse值作用:如果可能,边框会合并为一个单一的边框。会忽略 border-spacing 和 empty-cells 属性。 */
}
td,th{
padding: 10px;
/* 设置表格中单元格间距 */
}
</style>
</head>
<body>
<div id='app'>
<table>
<tr>
<th v-for="item_title in title">{{item_title}}</th>
<!-- 遍历表格标题 -->
</tr>
<tr v-for="item,index in books">
<!-- 遍历表格内容 -->
<th>{{index}}</th>
<th>{{item.name}}</th>
<th>{{item.date}}</th>
<th>{{'¥'+item.price.toFixed(2)}}</th>
<!-- toFixed作用:保留两位小数 -->
<th>
<button @click="redu(index)">-</button>
{{item.num}}
<button @click="add(index)">+</button>
</th>
<th>
<button @click="del(index)">移除</button>
</th>
</tr>
<tr>
<td colspan="6" style="text-align: right;">总价:{{total}}</td>
<!-- collapse='6'是合并6格 style作用是靠右显示-->
</tr>
</table>
</div>
<script>
new Vue({
el: '#app',
computed:{
total(){
let ret = this.books.reduce((pre,cur)=>{
return pre + cur.price*cur.num
},0)
return '¥'+ret.toFixed(2)+'元'
}
},
methods:{
add(i){
this.books[i].num++;
},
/*
redu(i){ // 标准写法
if(this.books[i].num===1){
return
}
this.books[i].num--;
}
*/
redu(i){ // 条件判断写法,三元运算符
this.books[i].num>1?this.books[i].num--:''
},
del(i){
this.books.splice(i,1)
}
},
data:{
title:['编号', '书籍名称', '出版日期', '价格', '数量', '操作'],
books:[
{
name:'算法导论',
date:'2006-9',
price:85,
num:1
},
{
name:'UNIX编程艺术',
date:'2006-2',
price:59,
num:1
},
{
name:'Vue程序设计',
date:'2008-10',
price:35,
num:1
},
{
name:'颈椎康复',
date:'2006-3',
price:139,
num:1
}
]
}
})
</script>
</body>
</html>