实现要求如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200810215150670.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5MjI1Mjcx,size_16,color_FFFFFF,t_70)
性能:能够修改购买数量按钮数量为自然数,移除操作会将一行移除,根据操作,下面的总价格会随之改变。基础数据存储为对象数组如下:
books:[
{
id:1,
name:"<<算法导论>>",
date:'2010-1',
price:20,
count:1
},
{
id:2,
name:"<<计算机导论>>",
date:'2010-2',
price:30,
count:1
},
{
id:3,
name:"<<操作系统>>",
date:'2010-3',
price:40,
count:1
},
{
id:4,
name:"<<计算机组成原理>>",
date:'2010-14',
price:50,
count:1
}
]
}
分析:
首先根据要求显示数据能够使用v-for对book进行遍历v-for=“item in books”,然后通过item.id等来显示td信息,然后对于每一行的需要添加一个+ ,-按钮以及数量显示,由于需要对item.count进行修改,所以需要传递index来修改对应id的count,通过v-on来实现,以及移除操作也通过v-on来实现对数组数据进行删除,由于数量不能为负数,所以需要样式,当数量小于1时不能点击,用disable属性来设置,当book内容为空时,界面应该显示购物车为空,用v-if和v-else来表示。而每个价格显示周围都有特定的符号,需要添加过滤器
过滤器
filters是一个对象,内部都是函数,数据传输进来进行过滤传输出去
在vue中定义:
filters:{//过滤器
showPrice(price){
return "¥"+price.toFixed(2);
}
}
调用方式:中间用| 隔开,前面为参数,后面为过滤器名字
{{item.price|showPrice}}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price|showPrice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.count<=1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="deleteBook(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>总价格:{{totalPrice|showPrice}}</h2>
</div>
<div v-else>
<h2>购物车为空</h2>
</div>
</div>
<script src="../js/vue.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
const app = new Vue({
el:'#app',
data:{
books:[
{
id:1,
name:"<<算法导论>>",
date:'2010-1',
price:20,
count:1
},
{
id:2,
name:"<<计算机导论>>",
date:'2010-2',
price:30,
count:1
},
{
id:3,
name:"<<操作系统>>",
date:'2010-3',
price:40,
count:1
},
{
id:4,
name:"<<计算机组成原理>>",
date:'2010-14',
price:50,
count:1
}
]
},
methods:{
getFinalPrice(price){
return price.toFixed(2);
},
decrement(index){
this.books[index].count--;
},
increment(index){
this.books[index].count++;
},
deleteBook(index){
this.books.splice(index,1);
}
},
filters:{//过滤器
showPrice(price){
return "¥"+price.toFixed(2);
}
},
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;
//使用高阶函数如下
return this.books.reduce((pre,book)=>pre+book.price*book.count,0);
}
}
});
style.css
table{
border:1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th,td{
padding: 8px 16px;
border:1px solid #e9e9e9;
text-align: center;
}
th{
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}