购物车案例思路:
1.将内容显示在页面上在data里定义一个数组,在tr里使用v-for指令循环遍历数组
2.价格以及总价格取两位小数两种方法:第一种使用函数,第二种使用过滤器,都需要使用toFixed()方法
在下面的案例中,单个价格使用的是方法一,总价格使用的是方法二。并且总价格的计算循环列举了四种方法,简便方法是第四种使用的是reduce高阶函数
3.书籍数量不能为负数,在数量那绑定表单中disabled方法,让数量小于等于0的时候禁用
4.增加、删除书籍数量是获得每本书的下标,指定书籍进行操作;移除按钮是使用数组的splice方法,第一个参数是要删除书籍信息的下标,第二个参数为1表示删除1个
5.所有书籍全部删除显示购物车为空使用v-if,v-else指令进行判断
说明:这个练习主要实现的功能是将数组以表格的形式显示在页面上,可以选择购买数量并将总价格显示在下面,但是如果数量为0不可以在点击减号,还可以将整行内容进行移除
HTML代码
<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>{{getFinalPrice(item.price)}}</td>
<td>
<button @click="sub(index)" :disabled="item.count<=0">-</button>
{{item.count}}
<button @click="add(index)">+</button>
</td>
<td><button @click="remove(index)">移除</button></td>
</tr>
</tbody>
</table>
<!-- 方法二:使用过滤器 -->
<h2>总价格:{{allPrice|showPrice}}</h2>
</div>
<h2 v-else>购物车为空</h2>
</div>
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;
}
JS代码
var app=new Vue({
el:"#app",
data:{
books:[
{
id:1,
name:'《算法导论》',
date:'2006-9',
price:85.00,
count:1
},
{
id:2,
name:'《计算机网络》',
date:'2006-2',
price:59.00,
count:1
},
{
id:3,
name:'《算法与数据结构》',
date:'2008-10',
price:39.00,
count:1
},
{
id:4,
name:'《操作系统》',
date:'2007-5',
price:55.00,
count:1
},
]
},
//方法一
methods: {
getFinalPrice(price){
return '¥'+price.toFixed(2)
},
add(index){
this.books[index].count++
},
sub(index){
this.books[index].count--
},
remove(index){
this.books.splice(index,1)
}
},
//方法二
filters:{
showPrice(price){
return '¥'+price.toFixed(2)
}
},
computed: {
allPrice(){
//1.for循环
// let allPrice=0
// for(let i=0;i<this.books.length;i++){
// allPrice+=this.books[i].price*this.books[i].count
// }
// return allPrice
//2.for in循环
// let allPrice=0
// for(let i in this.books){
// const book=this.books[i]
// allPrice+=book.price*book.count
// }
// return allPrice
//3.for of循环
// let allPrice=0
// for(let item of this.books){
// allPrice+=item.price*item.count
// }
// return allPrice
//4.reduce
return this.books.reduce(function(preValue,book){
return preValue+book.price*book.count
},0)
}
},
})