效果展示图:
效果展示
index.html
<div id="app">
<div v-if = "fruits.length">
<table>
<th>名称</th>
<th>日期</th>
<th>价格</th>
<th>数量</th>
<th>操作</th>
<tr v-for="(item, index) in fruits">
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price}}</td>
<td><button @click = "decrement(index)" v-bind:disabled = "item.count ===1">-</button> {{item.count}} <button @click="increment(index)">+</button></td>
<td><button @click = "removeItem(index)">移除</button></td>
</tr>
<tr><td>总价格:{{totalPrice | showPrice}}</td></tr>
</table>
</div>
<div v-else><img src="./img/empty_car.png" alt="购物车为空"></div>
</div>
style.css
table {
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table th,td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #03A9F4;
background-color: #b1ebf3;
}
main.js
const app = new Vue({
el:'#app',
data:{
fruits:
[
{
name : '苹果',
date :'2020-10-8',
price:25.50,
count:2
},
{
name :' 橘子',
date :'2020-12-1',
price:125.20,
count:1
},
{
name :' 香蕉',
date :'2020-11-21',
price:45.36,
count:4
},
{
name :' 榴莲',
date :'2020-11-20',
price:45.52,
count:4
}
],
},
methods:{
increment(index){
this.fruits[index].count++
},
decrement(index){
this.fruits[index].count--
},
removeItem(index){
this.fruits.splice(index,1)
},
},
computed:{
totalPrice(){
return this.fruits.reduce(function(privValue,fruits){
return privValue + fruits.count*fruits.price;
},0)
}
},
filters:{
showPrice(price){
return '¥' + price.toFixed(2);
}
}
})
学习笔记
- 当商品数量是1时,不能点击减少,使用
v-bind:disable
<td><button @click = "decrement(index)" v-bind:disabled = "item.count ===1">-</button>
- 商品总和使用过滤器
过滤器的使用格式<td>{{ 第一个是传的参数值 | 处理后的值}}</td>
在js中定义一个过滤器
filters:{
showPrice(price){
//保留两位小数
return '¥' + price.toFixed(2);
}
}
- 使用高阶函数filter、map、reduce
编程范式: 命令式编程/声明式编程
编程范式: 面向对象编程(第一公民:对象)/函数式编程(第一公民:函数)
filter/map/reduce
filter中的回调函数有一个要求: 必须返回一个boolean值
true: 当返回true时, 函数内部会自动将这次回调的n加入到新的数组中
false: 当返回false时, 函数内部会过滤掉这次的n
1.filter函数的使用,输出数组中大于40的数
const arr = [10, 20, 40,70,50,80,60]
let newNums = nums.filter(function (n) {
return n > 40
})
console.log(newNums);
2.map函数的使用,数组的数都乘以2
const arr = [10, 20, 40,70,50,80,60]
let new2Nums = newNums.map(function (n) {
return n * 2
})
console.log(new2Nums);//
3.reduce函数的使用,
reduce作用对数组中所有的内容进行汇总
let total = new2Nums.reduce(function (preValue, n) {
return preValue + n
}, 0)
console.log(total);