实现后的效果图:
购物车
*{
margin:0;
padding:0;
}
#app{
width:1200px;
margin:auto;
}
京东购物车
全选
商品
商品描述
单价
数量
小计
操作
{{item.bookName}}
¥{{item.price}}
{{ item.amount * item.price | fixed(2) }}
删除
总价:{{summary | fixed(2)}}
let vm = new Vue({
el:'#app',
filters:{ //管道函数 对管道符左侧的数据不操作 只改变在视图中的显示
fixed(value,num){ //第一个参数是管道符左侧的数据
return '¥'+value.toFixed(num)+'元'
}
},
data:{
checkAll:false, //计入全选框的状态
//下面是模拟的加入购物车的数据
products:[
{
isSelected:false, //计入复选框的状态,计算总价格时需要
imgUrl:"https://img10.360buyimg.com/cms/s80x80_jfs/t6094/107/710811867/382815/4d54717/592bf165N755a88f0.jpg", //商品图片
bookName:'深入浅出Node.js', //购物商品名
price: 54.50, //价格
amount:1, //购买数量
},
{
isSelected:false,
imgUrl:"https://img10.360buyimg.com/cms/s80x80_jfs/t9508/97/2285719018/62961/99c5b1b7/59f299b4Nc9e78adb.jpg",
bookName:'Vue.js实战',
price: 62.4,
amount:1,
}
]
},
//methods 内定义方法
methods: {
//全选按钮
selectAll(){
//forEach() 遍历数组 将所有的
this.products.forEach((item)=>{
item.isSelected = this.checkAll; //将 数组内数据的 所有复选框的状态 定义成全选框状态
})
},
//判断是否全选
selectSelected(){
//every() 遍历数组方法 如果数组每一项指定数据都为true 则返回true
this.checkAll = this.products.every((item)=>{
return item.isSelected
})
},
//删除数组内一条数据
remove(index){
this.products.splice(index,1); //从下标index开始删除products数组的1条数据
}
},
//computed 存计算属性
computed: {
summary(){
//reduce() //数组求和方法 (pre,next) pre表示总和 next表示数组下标
return this.products.reduce((pre,next)=>{
return pre + (next.isSelected? next.price*next.amount : 0)
},0) //0 表示pre初始为0
}
},
})